title: R - Count exact matches in string from list of words, then calculate overall sentiment using score per word
body: <p>I have a dataset containing a column of strings from which I wish to calculate an overall sentiment score, and a data frame containing all the unique words that appear in all the strings , each of which is assigned a score:</p>
  
  <pre><code>library(stringr)
  
  df &lt;- data.frame(text = c('recommend good value no problem','terrible quality no good','good service excellent quality commend'), score = 0)
  
  words &lt;- c('recommend','good','value','problem','terrible','quality','service','excellent','commend')
  scores &lt;- c(1,2,1,-2,-3,1,0,3,1)
  wordsdf &lt;- data.frame(words,scores)
  </code></pre>
  
  <p>The only way I have been able to get close to this is by using a nested for loop and the str_count function from the stringr package:</p>
  
  <pre><code>for (i in 1:3){
    count = 0
    for (j in 1:9){
      count &lt;- count + (str_count(df$text[i],as.character(wordsdf$words[j])) * wordsdf$scores[j])
    }
    df$score[i] &lt;- count
  }
  </code></pre>
  
  <p>This almost achieves what I want:</p>
  
  <pre><code>                                    text score
  1        recommend good value no problem     3
  2               terrible quality no good     0
  3 good service excellent quality commend     7
  </code></pre>
  
  <p>However, since the word 'commend' is also contained in the word 'recommend', my code calculates the scores as if both words are contained in the string.</p>
  
  <p>So I have two queries:
  1 - Is there a way to get it to match only to exact words?
  2 - Is there a way to achieve this without using the nested loop?</p>