在前面已经陆续总结了如何用 Python 和 JavaScript 建立词云了,今天要说的是 R。其实 SPSS 和 SAS 的 Word Cloud 扩展模板都是基于 R 实现的。html
1) 准备文本。git
咱们再…再次使用上次保存的 Word Cloud History.txt 的文本,这样咱们就能够在最后比较用各类方法生成词云的效果。(好吧,其实主要是懒,继续用吧……)github
2) 安装并加载所需的 R 包。dom
# Install install.packages("tm") # for text mining install.packages("wordcloud") # word-cloud generator install.packages("RColorBrewer") # color palettes # Load library("tm") library("wordcloud") library("RColorBrewer")
3) 读取并清洗文本数据。读取数据完毕咱们能够用 inspect()
来查看是否读取文本成功。函数
#Read text file text <- readLines(file.choose()) # Load the data as a corpus docs <- Corpus(VectorSource(text)) #Inspect the content #inspect(docs)[1:10]
4) 清洗数据。咱们将使用 tm_map()
函数来进行文本的大小写转换,清洗文本的空格符,常见停用词等。this
# Convert the text to lower case docs <- tm_map(docs, content_transformer(tolower)) # Remove numbers docs <- tm_map(docs, removeNumbers) # Remove english common stopwords docs <- tm_map(docs, removeWords, stopwords("english")) # Remove punctuations docs <- tm_map(docs, removePunctuation) # Eliminate extra white spaces docs <- tm_map(docs, stripWhitespace)
5) 用文本数据生成矩阵存放词语 (words) 及其频率 (frequencies) 。其中所用的 TermDocumentMatrix()
来自于 text mining 程序包。转换后咱们能够用 head()
来查看矩阵数据。spa
#Convert this into a matrix format m <- as.matrix(dtm) #Gives you the frequencies for every word v <- sort(rowSums(m),decreasing=TRUE) d <- data.frame(word = names(v),freq=v) #Scan the data #head(d, 10)
6) 生成 word cloud。code
wordcloud(words = d$word, freq = d$freq, scale=c(5,0.5), min.freq = 1, max.words=200, random.order=FALSE, rot.per=0.35, colors=brewer.pal(8, "Accent"))
若是要查看 wordcloud()
函数的各个参数的意义或者想给图形换个颜色,敲 help(wordcloud)
或者 help(RColorBrewer)
就能够查看帮助文档啦。orm