我不曾问过这个确切的问题-基于一个值(例如x[grepl("some string", x[["column1"]]),]
)的子集上有很多东西,但是没有多个值/字符串。
以下是我的数据示例:
#create sample data frame
data = data.frame(id = c(1,2,3,4), phrase = c("dog, frog, cat, moose", "horse, bunny, mouse", "armadillo, cat, bird,", "monkey, chimp, cow"))
#convert the `phrase` column to character string (the dataset I'm working on requires this)
data$phrase = data$phrase
#list of strings to remove rows by
remove_if = c("dog", "cat")
这将提供如下数据集:
id phrase
1 1 dog, frog, cat, moose
2 2 horse, bunny, mouse
3 3 armadillo, cat, bird,
4 4 monkey, chimp, cow
我要删除第1行和第3行(因为第1行包含“ dog”,第3行包含“ cat”),但保留第2行和第4行。
id phrase
1 2 horse, bunny, mouse
2 4 monkey, chimp, cow
换句话说,我想对data
进行子集设置,使它仅位于(标题和)第2行和第4行(因为它们既不包含“ dog”也不包含“ cat”)。
谢谢!
答案 0 :(得分:1)
使用grep
> data[grep(paste0(remove_if, collapse = "|"), data$phrase, invert = TRUE), ]
id phrase
2 2 horse, bunny, mouse
4 4 monkey, chimp, cow
答案 1 :(得分:1)
在grepl
将'remove_if'更改为单个字符串后,我们可以将subset
与paste
一起使用
subset(data, !grepl(paste(remove_if, collapse="|"), phrase))
# id phrase
#2 2 horse, bunny, mouse
#4 4 monkey, chimp, cow
答案 2 :(得分:1)
function eraseCookie(name) {
document.cookie = name+'=; Max-Age=-99999999;'; }
在此示例中构造的正则表达式为data[!grepl(paste0("(^|, )(", paste0(remove_if, collapse = "|"), ")(,|$)"), data$phrase),]
# id phrase
# 2 caterpillar, bunny, mouse
# 4 monkey, chimp, cow
,以避免匹配包含“ cat”或“ dog”但实际上不是确切单词的单词,例如“毛毛虫”
答案 3 :(得分:1)
如果您想将其与dplyr
和stringr
混合使用:
library(stringr)
library(dplyr)
data %>%
filter(str_detect(phrase, paste(remove_if, collapse = "|"), negate = TRUE))
# id phrase
# 1 2 horse, bunny, mouse
# 2 4 monkey, chimp, cow
答案 4 :(得分:0)
另一种方式(也许不是最好的方式):
data[-unique(unlist(sapply(c(remove_if),function(x){grep(x,data$phrase)}))),]
id phrase
2 2 horse, bunny, mouse
4 4 monkey, chimp, cow