Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Partial string matching subset

I have a data frame called LeaseDF. I am looking to pull all observations where the Team_Code column is contains the letter "t". The simple code I have is below. Somehow is not returning anything. I have also tried for loops with the grepl function and lapply with grepl to no avail. Thanks.

subset <- LeaseDF[grep("^t-", LeaseDF$TEAM_CODE),]
like image 891
Lyle Avatar asked Jul 16 '26 03:07

Lyle


1 Answers

I assume that with "pull" you mean subset?

As you didn't add your data I am giving you my example, where I used package sqldf

df <- data.frame(name = c('monday','tuesday','wednesday', 'thursday', 'friday'))
require(sqldf)
# Select specific values from a column i.e., containing letter "t"
sqldf("select * from df where name LIKE '%t%'")
# And output
     name
1  tuesday
2 thursday

Or use grep

df$name[grep("t", df$name) ]
# And output
[1] tuesday  thursday
Levels: friday monday thursday tuesday wednesday

# OR use ^t if you want beginning of the string
df[grep("^t", df$name), ] 

Or use grepl and you could also exclude non-matching observations

df[grepl("t", df$name), , drop = FALSE]
# Output
      name
2  tuesday
4 thursday
like image 88
Miha Avatar answered Jul 17 '26 18:07

Miha