0Pricing
R Academy · Lesson

Sentiment Analysis in R

Join tokens with sentiment lexicons to measure positive/negative tone.

Sentiment Analysis Overview

Sentiment analysis assigns emotional valence to text. The tidytext approach matches individual words against a sentiment lexicon and aggregates the scores. Three built-in lexicons are available: AFINN (numeric scores), Bing (positive/negative), and NRC (emotion categories).

library(tidytext)

# Available sentiment lexicons
# AFINN: -5 to +5 numeric score
# Bing:  binary positive/negative
# NRC:   emotion categories (joy, fear, anger, ...)

# Preview AFINN
afinn_sample <- get_sentiments('afinn')
cat('AFINN rows:', nrow(afinn_sample), '\n')
cat('Score range:', range(afinn_sample$value), '\n')
print(head(afinn_sample, 5))

get_sentiments('afinn')

The AFINN lexicon assigns integer scores from −5 (very negative) to +5 (very positive) to 2,477 English words. It was compiled by Finn Årup Nielsen and works well for social media and review text.

library(tidytext)
library(dplyr)

afinn <- get_sentiments('afinn')

# Most positive and most negative words
cat('Most positive words:\n')
print(afinn |> slice_max(value, n = 5))

cat('\nMost negative words:\n')
print(afinn |> slice_min(value, n = 5))

# Score distribution
cat('\nScore distribution:\n')
print(table(afinn$value))

All lessons in this course

  1. Tokenization and Stop Word Removal
  2. TF-IDF and Term Frequency Analysis
  3. Sentiment Analysis in R
  4. Topic Modeling with LDA
← Back to R Academy