如何稍微修改此代码以在R中生成正确的单词云?
假设我们有一个包含注释的数据框(如何稍微修改此代码以在R中生成正确的单词云?,r,sentiment-analysis,word-cloud,R,Sentiment Analysis,Word Cloud,假设我们有一个包含注释的数据框(df)(每一行都是注释): 我们有一本字典(dict),里面有肯定词和否定词: positive negative amazing terrible 我试图创建两个词云:一个是df中的积极评论,另一个是df中的消极评论。为此,我尝试了以下代码,但遇到了一个错误。有人能提出解决办法吗 library("quanteda") corpus_example <- corpus(df) head(corpus_example) Outpu
df
)(每一行都是注释):
我们有一本字典(dict
),里面有肯定词和否定词:
positive negative
amazing terrible
我试图创建两个词云:一个是df
中的积极评论,另一个是df
中的消极评论。为此,我尝试了以下代码,但遇到了一个错误。有人能提出解决办法吗
library("quanteda")
corpus_example <- corpus(df)
head(corpus_example)
Output:
text1:
"Amazing job"
text2:
"Terrible work"
库(“quanteda”)
例如,有几件事:
- 出现
正面
和负面
的原因是因为您已将惊人的工作
和糟糕的工作
映射到了相应的类别。我们使用字典将原始文本对应到不同的类别,以便以有意义的方式解释数据(例如,分析词频以了解情绪)
- 然而,我认为你根本不需要quanteda;请参见下面的示例,了解wordcloud的积极作用
- 由于要保留短语,请使用
table
;看
库(wordcloud)
df
library("quanteda")
corpus_example <- corpus(df)
head(corpus_example)
Output:
text1:
"Amazing job"
text2:
"Terrible work"
comments_dfm <- dfm(corpus_example, dictionary = dict)
head(comments_dfm)
Output:
positive negative
text1 1 0
text2 0 1
library(wordcloud)
df <- data.frame(comment = c("Amazing job",
"Terrible work",
"Great job",
"Great job",
"Great job",
"Great job",
"Fantastic job",
"Fantastic job",
"Fantastic job",
"Amazing job",
"Amazing job",
"Terrible work",
"Terrible work"))
dict <- list(
Positive = c("Amazing","Great","Fantastic"),
Negative = c("Terrible","Bad","Suck")
)
# finds positive comments / negative comments depending on input
find_matches <- function(comments,dictionary){
comments[grepl(paste(dictionary,collapse = "|"),
comments,
ignore.case = TRUE)]
}
# Since you want phrases, using table
positive_table <- table(find_matches(df$comment, dict$Positive))
wordcloud::wordcloud(
names(positive_table),
as.numeric(positive_table),
scale = c(2, 1),
min.freq = 3,
max.words = 100,
random.order = T
)