How to label text either positive or negative based on words in a dictionary in R?

Viewed 182

Suppose I have a vector (data frame) containing comments (each row is a different comment):

comment
'well done!'
'terrible work'
'quit your job'
'hi'

And I have the following data frame containing positive and negative words (i.e. a dictionary)

positive negative
well     terrible
done     quit

Is there a way in R to use this dictionary to label the comments in the first data frame either positive, negative or neutral depending on whether they contain more or less positive/negative comments?

I.e. I want the output to be a data frame that looks like:

comment          label
'well done!'     positive
'terrible work'  negative
'quit your job'  negative
'hi'             neutral

Does anyone know how this can be done in R?

1 Answers

Does this work:

library(dplyr)
library(stringr)
comm %>% mutate(label = case_when(str_detect(comments, str_c(dict$positive, collapse = '|')) ~ 'positive',
                                   str_detect(comments, str_c(dict$negative, collapse = '|')) ~ 'negative',
                                   TRUE ~ 'neutral'))
       comments    label
1    well done! positive
2 terrible work negative
3 quit your job negative
4            hi  neutral

Based on OP's requirement:

comm %>% mutate(p_count = str_count(comments, str_c(dict$positive, collapse = '|')), 
                 n_count = str_count(comments, str_c(dict$negative, collapse = '|'))) %>% 
           mutate(label = case_when(p_count > n_count ~ 'positive',
                                    p_count < n_count ~ 'negative',
                                    TRUE ~ 'neutral')) %>% select(comments, label)
                 comments    label
1              well done! positive
2      terrible well work  neutral
3 quit your job well well positive
4                      hi  neutral
5      terrible quit well negative

New data used:

comm
                 comments
1              well done!
2      terrible well work
3 quit your job well well
4                      hi
5      terrible quit well

dict
# A tibble: 2 x 2
  positive negative
  <chr>    <chr>   
1 well     terrible
2 done     quit    
Related