modifying polarity words in sentimentr package

571 Views Asked by At

Is there a way to modify words in the sentimentr package? For example I want to change the word "please" to have a negative score rather than a positive one. Now I'm using the function:

text$sentiment <- sentiment_by(text$Comment)

to evaluate sentence sentiment.

1

There are 1 best solutions below

7
xilliam On

One can modify the polarity dictionary used by the sentiment function of the sentimentr package as follows:

library(sentimenr)
library(lexicon)    

    # sample text
    text <- "Please please please, be nice."

    # output with default dictionary
    sentiment(text, polarity_dt = lexicon::hash_sentiment_jockers_rinker)

    # polarity of 'please' in default dictionary
    lexicon::hash_sentiment_jockers_rinker$y[lexicon::hash_sentiment_jockers_rinker$x %in% "please"]

    # create a modified dictionary
    mysentiment <- lexicon::hash_sentiment_jockers_rinker
    mysentiment$y[mysentiment$x %in% "please"] <- -1

    # modified polarity of 'please'
    mysentiment$y[mysentiment$x %in% "please"]

    # run sentiment with modified dictionary 
    sentiment(text, polarity_dt = mysentiment)

Similar results can be achieved with sentiment_by. And with either function it is possible to merge the text elements with the output:

    # sample text
    text <- data.frame(Comment = c(
      "Please please please, be nice.", 
      "You can please some of the people all of the time.",
      "You can please all of the people some of the time.", 
      "But you can’t please all of the people all of the time.",
      "Pleased to meet you, hope you guess my name."),
       stringsAsFactors = F)

    # add element_id column
    text$element_id <- 1:nrow(text)

    # run seniment_by with default dictionary
    sentiment_by(text$Comment, polarity_dt = lexicon::hash_sentiment_jockers_rinker)

    # polarity of please in default dictionary
    lexicon::hash_sentiment_jockers_rinker$y[lexicon::hash_sentiment_jockers_rinker$x %in% "please"]

    # create a modified dictionary
    mysentiment <- lexicon::hash_sentiment_jockers_rinker
    mysentiment$y[mysentiment$x %in% "please"] <- -1

    # modified polarity
    mysentiment$y[mysentiment$x %in% "please"]

    # run sentiment with modified dictionary 
    sentiments_modified <- sentiment_by(text$Comment, polarity_dt = mysentiment)

    # merge sentiment output with original text
    sentiments_tbl <- merge(sentiments_modified, text, by = "element_id")
    sentiments_tbl