如何从 wordcloud R 包中删除单词以便它们可以包含在输出中?

How to remove words from wordcloud R package so that they can be included in the output?

我正在使用来自 R 包存储库的包 "wordcloud" 和描述 "Word Cloud"。当我从一些随机文本创建 wordcloud 时,一些单词被自动省略,因为它们不应该是 wordcloud 的一部分。

代码:

library(RColorBrewer)
library(NLP)
library(wordcloud)
library(tm)


wordcloud("foo bar oh oh by by bye bingo hell no", scale=c(3,1), colors=brewer.pal(6,"Dark2"),random.order=FALSE)

输出:

我想在词云中保留 "oh" 和 "by" 这样的词。怎么样?

编辑:我更喜欢从 wordcloud 包的停用词集中删除这些词,而不是使用频率。

这是一种方法:

library(wordcloud)
library(tm)
txt <- "foo bar oh oh by by bye bingo hell no"
corp <- Corpus(VectorSource(txt))
tdm <- TermDocumentMatrix(corp, control = list(wordLengths = c(-Inf, Inf)))
m <- as.matrix(tdm)
v <- sort(rowSums(m),decreasing=TRUE)
d <- data.frame(word = names(v),freq=v)
wordcloud(d$word,d$freq,min.freq=1)

wordcloud()有两种使用方式:

  • 一个以所有单词作为主要参数的字符串:你现在做什么
  • 一个有单词向量和相应的频率向量

第一个输入强制 wordcloud() 调用 tm,构成语料库,删除停用词,这是你丢失两个字母单词的步骤。

一种简单的方法是恢复使用不需要 tm 包的 wordcloud,方法是在将字符串提供给 wordcloud() 之前对其进行处理:

library(stringr)
library(wordcloud)
library(RColorBrewer)

## The initial string
mystring <- "foo bar oh oh by by bye bingo hell no"
## Split it and count frequencies
tabl <- table(str_split(mystring,pattern=" "))
## Make the wordcloud: all words are there!
wordcloud(names(tabl),tabl,scale=c(3,1), colors=brewer.pal(6,"Dark2"),random.order=FALSE)