我有一个名为 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
关于R - 部分字符串匹配子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37869414/