Introduction
This article describes how to go from a standard word cloud:
To a state where sentiment is shown based on positive (green in this example) and negative (red in this example) scores:
Requirements
A data file that contains a variable with the phrases you wish to use to create the Word Cloud. Text variables are represented by a small a next to the variable in the Data Sets tree:
Method
- From the toolbar, go to Anything > Advanced Analysis > Text Analysis > Advanced > Setup Text Analysis.
- Select your text variable from the Text variable drop-down.
- Tick the Automatic option at the top.
- From the Data Sets tree, select your text variable.
- OPTIONAL: Update additional settings per step 3 in How to Set Up Text Analysis.
- Go to Anything > Advanced Analysis > Text Analysis > Sentiment.
- Go to Calculation > Custom Code.
- Paste in the code below:
# Sentiment analysis of the phrases
phrase.sentiment = `Sentiment scores from text.analysis.setup`
phrase.sentiment[phrase.sentiment >= 1] = 1
phrase.sentiment[phrase.sentiment <= -1] = -1
# Sentiment analysis of the words
final.tokens = text.analysis.setup$final.tokens
td = t(vapply(flipTextAnalysis:::decodeNumericText(text.analysis.setup$transformed.tokenized), function(x) {
as.integer(final.tokens %in% x)
}, integer(length(final.tokens))))
counts = text.analysis.setup$final.counts
phrase.word.sentiment = sweep(td, 1, phrase.sentiment, "*")
phrase.word.sentiment[td == 0] = NA # Setting missing values to Missing
word.mean = apply(phrase.word.sentiment,2, FUN = mean, na.rm = TRUE)
word.sd = apply(phrase.word.sentiment,2, FUN = sd, na.rm = TRUE)
word.n = apply(!is.na(phrase.word.sentiment),2, FUN = sum, na.rm = TRUE)
word.se = word.sd / sqrt(word.n)
word.z = word.mean / word.se
word.z[word.n <= 3 | is.na(word.se)] = 0
words = text.analysis.setup$final.tokens
x = data.frame(word = words,
freq = counts,
"Sentiment" = word.mean,
"Z-Score" = word.z,
Length = nchar(words))
word.data = x[order(counts, decreasing = TRUE), ]
# Working out the colors
n = nrow(word.data)
colors = rep("grey", n)
colors[word.data$Z.Score < -1.96] = "Red"
colors[word.data$Z.Score > 1.96] = "Green"
# Creating the word cloud
library(wordcloud2)
wordcloud2(data = word.data[, -3], color = colors, size = 0.4)
In the code above, you will need to replace `Sentiment scores from text.analysis.setup` on the second line of code with the name of your sentiment scores created in Step 5. You will also need to replace all instances of text.analysis.setup in the "# Sentiment analysis of the words" section of code with the name of text analysis object created in Steps 1-3.
See Also
Comments
0 comments
Article is closed for comments.