detect any pattern from a character vector within another character vector in R

Viewed 1177

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?

1 Answers

Another option is to collapse the pattern into a single string with |

library(stringr)
str_detect(lorem, str_c(c('non', 'sit'), collapse = "|"))
#[1]  TRUE FALSE FALSE  TRUE
Related