R - 部分字符串匹配子集

Lyl*_*yle 2 r dataframe rstudio

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

subset <- LeaseDF[grep("^t-", LeaseDF$TEAM_CODE),]
Run Code Online (Sandbox Code Playgroud)

Mih*_*iha 8

我认为“”是指子集?

由于你没有添加你的数据,我给你我的例子,我在那里使用了包 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
Run Code Online (Sandbox Code Playgroud)

或使用 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), ] 
Run Code Online (Sandbox Code Playgroud)

或者使用grepl,你也可以排除不匹配的观察

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