Find Emotions of Text Using R Code

0
232
views
emotion-analysis-in-r

Emotions analysis is part of the sentiment analysis. You can easily find the emotions of a given text by using the R Code.

PropellerAds

Find the emotions of the given text using this code. We can find the emotion of text and the polarity of the text eg. Positive, Negative and Neutral.

Packages Required

library(syuzhet)
library(twitteR)
library(devtools)
if(!require(Rstem)) install_url(“http://cran.r-project.org/src/contrib/Archive/Rstem/Rstem_0.4-1.tar.gz”)
if(!require(sentiment)) install_url(“http://cran.r-project.org/src/contrib/Archive/sentiment/sentiment_0.2.tar.gz”)
library(Rstem)
library(sentiment)
library(plotly)
library(dplyr)
library(wordcloud)

File Path
text <- readLines(“amazonreviews.csv”)   

emotions <- classify_emotion(text, algorithm=’bayes’)
polarities = classify_polarity(text, algorithm=’bayes’)

df = data.frame(text=text, emotion=emotions[,’BEST_FIT’],
               polarity=polarities[,’BEST_FIT’], stringsAsFactors=FALSE)
df[is.na(df)] <- “N.A.”

 

View Output in R Studio

View(df)

Export Output

xo<- as.matrix(df)
setwd(“E:/”)    
write.table(xo,file = ’emotions.csv’, sep = ‘,’, row.names = FALSE)

Plot the emotion Histogram

plot_ly(df, x=~emotion,type=”histogram”, marker = list(color = c(‘grey’, ‘red’,’orange’, ‘navy’,’yellow’))) %>%
layout(yaxis = list(title=’Count’), title=”Sentiment Analysis: Emotions”)

Plot the Positive Negative and Neutral Value Histogram
plot_ly(df, x=~polarity, type=”histogram”,
       marker = list(color = c(‘magenta’, ‘gold’,
                               ‘lightblue’))) %>%
 layout(yaxis = list(title=’Count’), title=”Sentiment Analysis: Polarity”)