Search code examples
rloopsfor-loopword-count

R loop for with grep function


Following code does not work:

I would like to loop over a list of word (array mdf) and find the number of occurences for each word in this list (mdf) in another list of words (array mydf). Thanks for your feedback!

for (x in mdf)
      { print 
      ( length(grep('x',mydf)))
   }

Solution

  • You can try something like:

    colSums(sapply(mdf, grepl, mydf))
    

    Here is a demo:

    colSums(sapply(c("a", "b", "c"), grepl, c("a", "a", "b")))
    a b c 
    2 1 0
    

    Which says a, b and c appears 2, 1 and 0 times in the other array.