【发布时间】:2021-12-08 06:44:11
【问题描述】:
我想提取必须包含两个或多个部分字符串的行。例如,假设我有以下data.table
df <- data.table(player = c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
position = c('S Guard', 'P Guaaard', 'P Guard', 'S Forward',
'P Forward', 'Center', 'Center'),
points = c(28, 17, 19, 14, 23, 26, 5))
我知道我可以使用部分字符串Gua 或rd 提取行
df[grep("Gua|rd", df$position), ]
如果我希望字符串同时包含Gua 和 rd,该怎么办?试过了
df[grep("Gua&rd", df$position), ]
无论有无空格,但都不起作用。
编辑更多信息
我实际上正在处理相对较大的数据集,并且我在一个中使用字符串从另一个中提取数据,如下所示:
df1 <- data.frame(player = c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
position1 = c('S Guard', 'P Guard', 'P Guard', 'S Forward',
'P Forward', 'Center', 'Center'),
position2 = c('S Grd', 'P Guard', 'P rdGua', 'S Forward',
'P Forward', 'Center', 'Center'))
df2 <- data.table(player = c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
points = c(28, 17, 19, 14, 23, 26, 5))
df2[df1[,3] %like% "Gua|rd",c(1,2)]
因此顺序无关紧要,即如果使用& 代替|,Guard 和rdGua 应该返回true。
【问题讨论】:
-
我相信有人会给你一个巧妙的正则表达式答案,但与此同时,这将起作用:
df[grepl("Gua", df$position) & grepl("rd", df$position), ] -
我看到您对我的答案提出的修改,并附有以下评论 “问题中给出的列表语法,而不是数据框语法。”。我拒绝了那个编辑。澄清一下:您也可以在 data.frames 上使用列表语法,我个人更喜欢列表语法。
标签: r dplyr grep data.table