Sentiment analysis in R

[This article was first published on R Programming – DataScience+, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Category

Tags

There are many ways to perform sentiment analysis in R, including external packages. Most of those common methods are based on dictionary lookups that allow calculating sentiment based on static data. This approach, however, does not measure the relations between words and negations being spanned in different parts of the sentence. That often ends up in a lot of false positives, not to mention irony sentences being interpreted incorrectly…

Let’s do some coding now. For the purpose of this article, we use Microsoft R Tools (part of the Visual Studio components). Once this is installed, we open R Interactive window and attach the debugger.

Next step is to create free account at text2data in order to get the API key and secret. Once you get that, just configure the script below with these api key and secret and hit enter!

The code below invokes text2data API to display sentiment results in your R environment:

library(httr)
 
url <- "http://api.text2data.com/v3/analyze"
       requestBody <- list(
  DocumentText = "Excellent location, opposite a very large mall with wide variety of shops, restaurants and more.",
  IsTwitterContent = "false",
  UserCategoryModelName = "",
  PrivateKey = "------------",#add your private key here (you can find it in the admin panel once you sign-up)
  Secret= "" #this should be set-up in admin panel as well
)
#make POST request
res <- httr::POST(url = url,body = requestBody, encode = "json")
 
#read response
json <- httr::content(res, as = "text")
respData <- jsonlite::fromJSON(json)
 
#display results
if(respData$Status == 1)
{
    print(
     sprintf("This document is: %s %s%.2f", respData$DocSentimentResultString, respData$DocSentimentPolarity, respData$DocSentimentValue)
    )
    print(
     sprintf("Magnitude is: %.2f", respData$Magnitude)
    )
    print(
     sprintf("Subjectivity is: %s", respData$Subjectivity)
    )
 
 
} else{
   print(respData$ErrorMessage)
}

text2data.com

Related Post

To leave a comment for the author, please follow the link and comment on their blog: R Programming – DataScience+.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)