Analyzing Social Media Data in R
Vivek Vijayaraghavan
Data Science Coach
# Extract tweets on galaxy fold
twts_galxy <- search_tweets("galaxy fold", n = 5000,
lang = "en", include_rts = FALSE)
# Perform sentiment analysis for tweets on galaxy fold
library(syuzhet)
sa.value <- get_nrc_sentiment(twts_galxy$text)
# View the sentiment scores
sa.value[1:5,1:7]
anger anticipation disgust fear joy sadness surprise
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
0 0 0 0 0 0 0
1 0 0 0 0 0 0
1 1 0 2 1 1 1
0 0 0 1 0 0 0
0 0 0 0 0 0 0
# Calculate sum of sentiment scores
score <- colSums(sa.value[,])
# Convert to data frame
score_df <- data.frame(score)
# View the data frame
score_df
score
<dbl>
anger 211
anticipation 825
disgust 214
fear 253
joy 412
sadness 197
surprise 315
trust 641
negative 487
positive 1351
# Convert row names into 'sentiment' column
# Combine with sentiment scores
sa.score <- cbind(sentiment = row.names(score_df),
score_df, row.names=NULL)
# View data frame with sentiment scores
print(sa.score)
sentiment score
<fct> <dbl>
anger 211
anticipation 825
disgust 214
fear 253
joy 412
sadness 197
surprise 315
trust 641
negative 487
positive 1351
ggplot()
# Plot the sentiment scores
ggplot(data = sa.score2, aes(x = sentiment, y = score,
fill = sentiment)) +
geom_bar(stat = "identity") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
Analyzing Social Media Data in R