I need help debugging this R code for a Reddit sentiment analysis

Learning Goal: I’m working on a r project and need an explanation and answer to help me learn.

library(RedditExtractoR)

library(radarchart)

library(tm)

library(syuzhet)

library(plyr)

library(dplyr)

library(lubridate)

# Getting Reddit Data

links<- find_thread_urls(Keywords = “Ghostbusters Afterlife”,

sort_by = “comments”,

subreddit = NA,

period = “all”)

# function to iterate through all posts

content = get_thread_content(links$URL)

funct = function(i){

com = iconv(content$comments, to = ‘utf-8’)

clov = get_nrc_sentiment(com)

x1 = 100*colSums(clov)/sum(clov)

return(cbind(links[i,], t(x1) ))

}

# list of all the links

ls = list(1:nrow(links))

# loop through all the links and bind to a data frame

out = lapply(ls, funct)

res = do.call(“rbind”,lapply(ls, funct) )

res$date <- as.Date(res$date, “%d-%m-%y”)

# aggregate data by month

res$month = floor_date(res$date, “month”)

# summarize all results

xx = res %>% group_by(month) %>% summarise(positive = mean(positive), negative = mean(negative)) %>% as.data.frame()

# plot results

barplot(xx[,2:3] %>% as.matrix() %>% t(), col=c(“green”,”red”), main = “Sentiment history”, names.arg = xx$month, xlab = “Month”, ylab = “Sentiment”)

opinion.lexicon.pos = scan(‘positive.txt’, what=’character’, comment.char=’;’)

opinion.lexicon.neg = scan(‘negative.txt’, what=’character’, comment.char=’;’)

head(opinion.lexicon.neg) # look at first few negative words

head(opinion.lexicon.pos) # look at first few positive words

# Create getSentimentScore function that will calculate the sentiment score for each tweet

getSentimentScore = function(sentences, words.positive, words.negative, .progress=’none’)

{

require(plyr) # Require plyr package

require(stringr) # Require stringr package

scores = laply(sentences, function(sentence, words.positive, words.negative) {

# Let first remove the Digit, Punctuation character and Control characters:

sentence = gsub(‘[[:cntrl:]]’, ”, gsub(‘[[:punct:]]’, ”, gsub(‘\\d+’, ”, sentence)))

# Then lets convert all to lower sentence case:

sentence = tolower(sentence)

# Now lets split each sentence by the space delimiter

words = unlist(str_split(sentence, ‘\\s+’))

# Get the boolean match of each words with the positive & negative opinion-lexicon

pos.matches = !is.na(match(words, words.positive))

neg.matches = !is.na(match(words, words.negative))

# Now get the score as total positive sentiment minus the total negatives

score = sum(pos.matches) – sum(neg.matches)

return(score)

}, words.positive, words.negative, .progress=.progress )

# Return a data frame with respective sentence and the score

return(data.frame(text=sentences, score=scores))

}

# Calculate a raw sentiment score for each tweet about a movie using the getSentimentScore function

RedditResults = getSentimentScore(links, opinion.lexicon.pos, opinion.lexicon.neg)

View(RedditResults) # View results

# Create a histogram showing the distribution of the raw sentiment scores for each movie

dates$Date <- as.Date(dates$Date)

ggplot(Reddit$Results, aes(x=Date)) + geom_histogram(binwidth=30, colour=”blue”) +

scale_x_date(labels = date_format(“%Y-%b”),

breaks = seq(min(dates$Date)-5, max(dates$Date)+5, 30),

limits = c(as.Date(“2021-10-01”), as.Date(“2021-11-01”))) +

ylab(“Frequency”) + xlab(“Year and Month”) +

theme_bw() + opts(axis.text.x = theme_text(angle=90))

# Install and load psych package

install.packages(‘psych’)

library(‘psych’)

# Calculate descriptive stats for raw sentiment scores for each movie

describe(RedditResults$score)

FYI – I have already had one tutor who was not able to complete the question and fix my code.

Place your order
(550 words)

Approximate price: $22

Calculate the price of your order

550 words
We'll send you the first draft for approval by September 11, 2018 at 10:52 AM
Total price:
$26
The price is based on these factors:
Academic level
Number of pages
Urgency
Basic features
  • Free title page and bibliography
  • Unlimited revisions
  • Plagiarism-free guarantee
  • Money-back guarantee
  • 24/7 support
On-demand options
  • Writer’s samples
  • Part-by-part delivery
  • Overnight delivery
  • Copies of used sources
  • Expert Proofreading
Paper format
  • 275 words per page
  • 12 pt Arial/Times New Roman
  • Double line spacing
  • Any citation style (APA, MLA, Chicago/Turabian, Harvard)

Our guarantees

Delivering a high-quality product at a reasonable price is not enough anymore.
That’s why we have developed 5 beneficial guarantees that will make your experience with our service enjoyable, easy, and safe.

Money-back guarantee

You have to be 100% sure of the quality of your product to give a money-back guarantee. This describes us perfectly. Make sure that this guarantee is totally transparent.

Read more

Zero-plagiarism guarantee

Each paper is composed from scratch, according to your instructions. It is then checked by our plagiarism-detection software. There is no gap where plagiarism could squeeze in.

Read more

Free-revision policy

Thanks to our free revisions, there is no way for you to be unsatisfied. We will work on your paper until you are completely happy with the result.

Read more

Privacy policy

Your email is safe, as we store it according to international data protection rules. Your bank details are secure, as we use only reliable payment systems.

Read more

Fair-cooperation guarantee

By sending us your money, you buy the service we provide. Check out our terms and conditions if you prefer business talks to be laid out in official language.

Read more