I would like to return a logical vector with TRUE values for all elements in which any element from another character vector is detected.
Example data:
lorem <- c("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.",
"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
As an example, I would like to search the elements 'sit' and 'non'.
I tried
str_detect(lorem, c('sit', 'non'))
and
str_detect(lorem, c('non', 'sit'))
which showed me that the second argument is probably being recycled, so the call str_detect(lorem, c('sit', 'non')) actually occurs as follows:
c(str_detect(lorem[1], 'sit'), str_detect(lorem[2], 'non'), str_detect(lorem[3], 'sit'), str_detect(lorem[4], 'non'))
I eventually came up with the following solution:
multi_string_detect<-function(x,y){
temp<-sapply(y, function(z){str_detect(x, z)})
apply(temp, 1, any)
}
multi_string_detect(lorem, c('sit', 'non')
[1] TRUE FALSE FALSE TRUE
Is there a clean/simpler alternative to my multi_string_detect function?