【发布时间】:2021-04-23 03:25:14
【问题描述】:
我正在寻找一种方法,将两个不同的逻辑条件(包含和排除语句)应用于字符串,并获得一个逻辑向量作为输出:
我可以用以下代码做到这一点:
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 的合成器在一次调用中创建最终向量。
我试过了
I tried to use `fruits%>%str_detect(., 'apple') & str_detect(., 'orange, negate=TRUE)
但是失败了,得到了一个“òbject '。”未找到”声明
-有一个更简单的 regex/stringr 解决方案,可以避免调用两个不同的 str_detect 函数
建议?
【问题讨论】: