trinker / sentimentr

Dictionary based sentiment analysis that considers valence shifters
Other
426 stars 84 forks source link

how to calculate sum of sentiment? #122

Closed sadettindemirel closed 2 years ago

sadettindemirel commented 3 years ago

Hello Tyler, First and foremost thank you for this package, it is a lifesaver. I have a quick question. How can I get the total sum of sentiment in the text instead of ave_sentiment?

Thanks in advance Best

trinker commented 2 years ago

You can pass your own averaging function in as shown in the 2nd example below:

library(sentimentr)

presidential_debates_2012 %>%
    get_sentences() %>%
    sentiment_by(
        by = c('person', 'time')
    )

##        person   time word_count        sd ave_sentiment
##  1:     OBAMA time 1       3599 0.2535006    0.12256892
##  2:     OBAMA time 2       7477 0.2509177    0.11217673
##  3:     OBAMA time 3       7243 0.2441394    0.07975688
##  4:    ROMNEY time 1       4085 0.2525596    0.10151917
##  5:    ROMNEY time 2       7536 0.2205169    0.08791018
##  6:    ROMNEY time 3       8303 0.2623534    0.09968544
##  7:   CROWLEY time 2       1672 0.2181662    0.19455290
##  8:    LEHRER time 1        765 0.2973360    0.15473364
##  9:  QUESTION time 2        583 0.1756778    0.03197751
## 10: SCHIEFFER time 3       1445 0.2345187    0.08843478

presidential_debates_2012 %>%
    get_sentences() %>%
    sentiment_by(
        by = c('person', 'time'), 
        averaging.function = function(x) sum(x)
    )

##        person   time word_count        sd ave_sentiment
##  1:     OBAMA time 1       3599 0.2535006    16.4202565
##  2:     OBAMA time 2       7477 0.2509177    37.1597713
##  3:     OBAMA time 3       7243 0.2441394    23.3033869
##  4:    ROMNEY time 1       4085 0.2525596    19.3014789
##  5:    ROMNEY time 2       7536 0.2205169    31.1475733
##  6:    ROMNEY time 3       8303 0.2623534    41.1951491
##  7:   CROWLEY time 2       1672 0.2181662    15.0046741
##  8:    LEHRER time 1        765 0.2973360     8.1865305
##  9:  QUESTION time 2        583 0.1756778     0.9153409
## 10: SCHIEFFER time 3       1445 0.2345187     7.2514085