我想使用 filter() 和 str_detect() 匹配多个模式来过滤数据帧,而不需要多次调用 str_detect() 函数。在下面的示例中,我想过滤数据框
df
以仅显示包含字母 a
f
和 o
的行。
df <- data.frame(numbers = 1:52, letters = letters)
df %>%
filter(
str_detect(.$letters, "a")|
str_detect(.$letters, "f")|
str_detect(.$letters, "o")
)
# numbers letters
#1 1 a
#2 6 f
#3 15 o
#4 27 a
#5 32 f
#6 41 o
我已尝试以下
df %>%
filter(
str_detect(.$letters, c("a", "f", "o"))
)
# numbers letters
#1 1 a
#2 15 o
#3 32 f
并收到以下错误
警告消息:在 stri_detect_regex(string, pattern, opts_regex = opts(pattern)) :较长的对象长度不是较短对象的倍数 物体长度
使用 filter() 和 str_detect() 完成此操作的正确语法是
df %>%
filter(
str_detect(letters, "a|f|o")
)
# numbers letters
#1 1 a
#2 6 f
#3 15 o
#4 27 a
#5 32 f
#6 41 o
这可以用“&”而不是“|”来实现吗? (抱歉没有足够的代表发表评论)
为了进一步综合接受的答案,还可以定义一个具有感兴趣的搜索模式的向量,并使用其
paste
参数将这些向量与 collapse
连接起来,其中搜索标准 'or' 定义为 '|'
且搜索条件 'and' 为 '&'
.
这可能很有用,例如,当搜索模式在脚本中的其他位置自动生成或从源读取时。
#' Changing the column name of the letters column to `lttrs`
#' to avoid confusion with the built-in vector `letters`
df <- data.frame(numbers = 1:52, lttrs = letters)
search_vec <- c('a','f','o')
df %>%
filter(str_detect(lttrs, pattern = paste(search_vec, collapse = '|')))
# numbers letters
#1 1 a
#2 6 f
#3 15 o
#4 27 a
#5 32 f
#6 41 o