I am trying to modify the sentiment of a few specific words in my df to make them more suitable for my context, where they were used with a negative connotation but have been classified as having a positive sentiment. The words are "talent" and "prefer".
Here is my code:
#Loading packages
library(dplyr)
library(ggplot2)
require(readxl)
library(tidytext)
require(writexl)
data example:
dput(sentiment_words[1:20,c(7,8,9)])
data output:
structure(list(word = c("talent", "prefer", "lies", "hard", "worsen",
"addicts", "obnoxious", "unbearable", "sickening", "irritating",
"weird", "inconsiderate", "weird", "overwhelming", "issue", "complaints",
"confined", "love", "confined", "idiots"), sentiment = c("positive",
"positive", "negative", "negative", "negative", "negative", "negative",
"negative", "negative", "negative", "negative", "negative", "negative",
"negative", "negative", "negative", "negative", "positive", "negative",
"negative"), count = c(79L, 3L, 53L, 316L, 2L, 2L, 3L, 2L, 2L,
7L, 24L, 2L, 24L, 2L, 198L, 21L, 4L, 52L, 4L, 19L)), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -20L), groups = structure(list(
word = c("addicts", "complaints", "confined", "ftw", "hard",
"idiots", "inconsiderate", "irritating", "issue", "lies",
"lost", "love", "obnoxious", "overwhelming", "sickening",
"unbearable", "weird", "worsen"), .rows = structure(list(
6L, 16L, c(17L, 19L), 2L, 4L, 20L, 12L, 10L, 15L, 3L,
1L, 18L, 7L, 14L, 9L, 8L, c(11L, 13L), 5L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -18L), .drop = TRUE))
###### Sentiment Analysis by Word ######
## Using "TIDYTEXT" sentiment dictionary
sentiment_words <- df |>
tidytext::unnest_tokens(output="word", input="post") |>
dplyr::anti_join(tidytext::stop_words)|>
dplyr::inner_join(tidytext::get_sentiments("bing"))
sentiment_words %>%
count(word, sort = TRUE)
# Check the Most common positive and negative words
sentiment_words <-
sentiment_words %>% group_by(word) %>% mutate(count = n())
bing_word_counts <- sentiment_words %>%
dplyr::inner_join(tidytext::get_sentiments("bing") %>%
count(word, sentiment, sort = TRUE))
get_sentiments("bing")
returns a regular tibble with 2 string columns that you can filter and wrangle as you see fit:Though there's no magic involved, so "prefers" and "talents" are still classified as positives, which may or may not be what you are after:
When you have applied all required modification to your sentiment table, use that (
sentiments_mod
) in your workflow:Created on 2023-11-28 with reprex v2.0.2