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



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

我可以用以下代码完成:

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))

解决方案1:

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

解决方案2:

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

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

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

我试过

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

但是失败了,得到了一个";对象"."未找到";报表

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

建议?

可以使用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

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

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

最新更新