R - 部分字符串匹配子集

R - Partial string matching subset

我有一个名为 LeaseDF 的数据框。我希望提取 Team_Code 列包含字母 "t" 的所有观察结果。我的简单代码如下。不知何故没有返回任何东西。我还尝试了使用 grepl 函数的循环和使用 grepl 的 lapply 无济于事。谢谢。

subset <- LeaseDF[grep("^t-", LeaseDF$TEAM_CODE),]

我假设“pull”是指子集?

因为你没有添加你的数据,我给你我的例子,我使用包 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

或使用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), ] 

或使用 grepl,您还可以排除不匹配的观察结果

df[grepl("t", df$name), , drop = FALSE]
# Output
      name
2  tuesday
4 thursday