I am working on a function that will hopefully perform a sentiment analysis for each emotion in the NRC dictionary on a list (see: https://www.tidytextmining.com/sentiment.html#sentiment-analysis-with-inner-join), and then save the score itself as a variable in a dataframe or tibble. I've got the actual analysis part down, but saving it in the dataframe or tibble is not working.
#Creating List of All Emotions To Apply This To
emotion <- c('anger', 'disgust', 'joy', 'surprise', 'anticip', 'fear', 'sadness', 'trust')
#Initialize List with Length of Emotion Vector
wcount <- vector("list", length(emotion))
#Create Tibble for me to Deposit the Result Into
nrc_tib <-tibble(id="",
anger=numeric(0),
disgust=numeric(0),
joy=numeric(0),
surprise=numeric(0),
anticip=numeric(0),
fear=numeric(0),
sadness=numeric(0),
trust=numeric(0))
#Create Row to Deposit Variable Into
nrc_tib <-add_row(nrc_tib, 'id'="transcript1.txt")
#Defining Function
sentimentanalysis_nrc <- function(emoi) {
#Getting Sentiment, Filtering by Emotion in List
nrc_list <- get_sentiments("nrc") %>%
filter(sentiment == emoi)
#Conducting Sentiment Analysis, Saving Results
wcount[[emoi]] <- wordcount %>%
inner_join(nrc_list) %>%
count(word, sort = TRUE)
#Calculating Sentiment Score for Given Emotion
score <- sum(wcount[[emoi]]$n)
#Saving Emotion in nrc_tib, which is the part that doesn't work
nrc_tib$emoi <- score
}
#Running the Function
lapply(emotion, FUN = sentimentanalysis_nrc)
I've tried a few different things, including putting emoi in brackets in the line that doesn't work, and some googling suggests that isn't allowed. What would be allowed if I wanted to save it?
Note: If this helps for context...this example uses the file transcript1.txt, but my goal eventually is to generalize this across transcript2.txt-transcript45.txt, binding the scores for all 45 transcripts together afterwards.
EDIT: I came up with a clunky solution, using:
nrc_tib <<- replace(nrc_tib, emoi, score)
But there's got to be a better solution than that.