将多个逻辑函数应用于字符串以获得单个最终逻辑向量

apply multiple logical functions to string to obtain a single final logical vector

我正在寻找一种方法将两个不同的逻辑条件(包含和排除语句)应用于字符串,并获得逻辑向量作为输出:

我可以用下面的代码做到这一点:

library(purrr)
library(stringr)

fruits<-c('apple', 'banana', NA, 'orange and apple')

conditions<-list(detect=function(x)str_detect(x,'apple'),
                 exclude=function(x)str_detect(x,'orange', negate=TRUE))

解决方案一:

map_lgl(fruits, ~c(conditions[[1]](.) & conditions[[2]](.)))
>[1]  TRUE FALSE    NA FALSE

方案二:

Reduce("&", map(conditions, ~.(fruits)))
>[1]  TRUE FALSE    NA FALSE

这显然很冗长,因为我必须定义和调用这两个函数,然后使用两个循环(map()Reduce())。

我想知道是否:
- 有一种更简单的方法可以在一次调用中使用某种类似 purrr 的合成器调用这两个函数来创建最终向量。

我试过了

I tried to use `fruits%>%str_detect(., 'apple') & str_detect(., 'orange, negate=TRUE)

但是失败了,得到了一个“òbject”。未找到”声明

-有一个更简单的 regex/stringr 解决方案可以避免调用两个不同的 str_detect 函数

建议?

您存储 conditions 的方式使循环(mapReduce)成为必要。为什么要将它存储在列表中?这些是矢量化函数,可以以矢量化的方式应用。

library(stringr)
str_detect(fruits, 'apple') & str_detect(fruits, 'orange', negate = TRUE)
#[1]  TRUE FALSE    NA FALSE

可以使用grepl和一个正则表达式来做到这一点:

fruits<-c('apple', 'banana', NA, 'orange and apple')
grepl("^(?!.*\borange\b).*\bapple\b.*$", fruits, perl=TRUE)

[1]  TRUE FALSE FALSE FALSE

但是,我可能会在这里对 grepl 进行两次单独的调用:

grepl("\bapple\b", fruits) & !grepl("\borange\b", fruits)
[1]  TRUE FALSE FALSE FALSE