Keyword searching a character string

Viewed 138

Say I have sample strings

sample1 <- "i have a nasty cough today"
sample2 <- "do yall like nasty burgers" 

I want to check if it has the noun I am looking for AND the other relevant keyword. For example:

nouns <- c("i", "you", "we")
keywords <- c("cough", "tomorrow", "nasty")

The function should return TRUE to function(sample1) and FALSE to function(sample2) because sample2 does NOT have a noun from my specified vector, even if it has a keyword.

I am familiar with str_contains() from the sjmisc package, but am unsure how to extend it to combinations of two vectors.

2 Answers

You can combine nouns and keywords into one pattern and check if both of them are present in the string.

nouns <- c("i", "you", "we")
keywords <- c("cough", "tomorrow", "nasty")

check_keyword <- function(x) {
grepl(paste0('\\b', nouns, '\\b', collapse = '|'), x) & 
  grepl(paste0('\\b', keywords, '\\b', collapse = '|'), x)
}

sample1 <- "i have a nasty cough today"
sample2 <- "do yall like nasty burgers" 

check_keyword(sample1)
#[1] TRUE
check_keyword(sample2)
#[1] FALSE

You could put both, keywords and samples into lists. For the former we apply a function mkPat simultaneously that already prepares the needed patterns.

mkPat <- function(x) do.call(paste, c(list(paste0("\\b", x, "\\b")), collapse="|"))

kw <- lapply(list(nouns, keywords), mkPat)
smp <- list(sample1, sample2, sample3)

Then we can easily use sapply

sapply(kw, grepl, smp)
#       [,1]  [,2]
# [1,]  TRUE  TRUE
# [2,] FALSE  TRUE
# [3,] FALSE FALSE

and look where the rowSums (of TRUEs) equal to 2.

rowSums(sapply(kw, grepl, smp)) == 2
# [1]  TRUE FALSE FALSE

Data:

sample1 <- "i have a nasty cough today"
sample2 <- "do yall like nasty burgers" 
sample3 <- "do yall like tasty burgers" 
Related