I am looking for a way to apply two different logical conditions (an inclusion and an exclusion statement) to a string, and obtain a logical vector as output:
I was able to do it with the following code:
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))
Solution 1:
map_lgl(fruits, ~c(conditions[[1]](.) & conditions[[2]](.)))
>[1] TRUE FALSE NA FALSE
Solution 2:
Reduce("&", map(conditions, ~.(fruits)))
>[1] TRUE FALSE NA FALSE
This is obviously quite verbose, because I had to define and call these two functions, then use two loops (map()
and Reduce()
).
I wonder if:
-There is a simpler way to call these two functions to create the final vector using some sort of purrr-like synthax, in a single call.
I tried
I tried to use `fruits%>%str_detect(., 'apple') & str_detect(., 'orange, negate=TRUE)
But failed, got an "òbject '.' not found" statement
-There is a simpler regex/stringr solution that would avoid calling two different str_detect
functions
Suggestions?