我建议使用循环进行此类操作。在我看来,这样更加灵活多变。
一个示例是
httpdf 表格(也是为了回答 RxT 的评论):
httpdf <- tibble(
payload = c(
"the createor is nice",
"try to create something to select",
"never catch a dropping knife",
"drop it like it's hot",
NA,
"totaly unrelated" ),
other_optional_columns = 1:6 )
我使用sapply循环遍历搜索查询,并将每个字符串作为单独的模式应用于str_detect。这将返回一个矩阵,其中每个搜索查询字符串对应一列,每个主题字符串对应一行,可以折叠以返回所需的逻辑向量。
queries1 <-
httpdf[
sapply(
c("create", "drop", "select"),
str_detect,
string = httpdf$payload ) %>%
rowSums( na.rm = TRUE ) != 0, ]
当然,它可以被包装在一个函数中,在 tidyverse 过滤器内使用:
str_detect_mult <-
function( subject, query ) {
sapply(
query,
str_detect,
string = subject ) %>%
rowSums( na.rm = TRUE ) != 0
}
queries1 <- httpdf %>% filter( str_detect_mult( payload, c("create", "drop", "select") ) )
如果您想要精确匹配单词,可以轻松处理单词边界(“\\b”匹配单词边界并连接到字符串的开头和结尾):
str_detect_mult_exact <-
function( subject, query ) {
sapply(
query,
function(.x)
str_detect(
subject,
str_c("\\b",.x,"\\b") ) ) %>%
rowSums( na.rm = TRUE ) != 0
}
轻松处理多个匹配项(例如,如果您只想要匹配恰好一个字符串的行,即异或):
str_detect_mult_xor <-
function( subject, query ) {
sapply(
query,
str_detect,
string = subject ) %>%
rowSums( na.rm = TRUE ) == 1
}
在基本的R中也适用:
str_detect_mult <-
function( subject, query ) {
rowSums(sapply(
query,
grepl,
x = subject ), na.rm = TRUE ) != 0
}
queries1 <- httpdf[ str_detect_mult( httpdf$payload, c("create", "drop", "select") ), ]
paste(c('create', 'drop', 'select'), collapse="|")
的代码。 - akrun