Finding matches between each element of a list of strings and each string of a vector in R (avoiding 'for')

Viewed 521

I have two columns in a data frame with strings that I want to compare. The first one is a vector of strings and the second one is a list with a mini vector of strings in each element. Imagine to have a data frame like this one:

    V                 L 
"Anameone"     "name" "asd" 
"Bnametwo"         "dfg"
"Cnamethree"   "hey" "C" "hi"

I would like to see if some of the words in the first element of L appears in the first element of V, if some of the words in the second element of L appears in the second element of V... and so on.

I could do what I wanted with a loop like this:

for (i in c(1:3)){ df$matches[i] <- any(df$L[[i]],grepl, df$V[i],ignore.case = T)) }

So that the output is:

> df$matches
[1] "TRUE"  "FALSE" "TRUE"

But actually I have around 100.000 instead of 3 rows and it takes too long indeed. I haven't been able to figure out how to do this a bit more efficiently, any ideas? All my other attempts without using indexs ended up with what would be a matrix 3x3 in this example because it compares "all with all", and I think this could be still worse than a for.

3 Answers
Related