设为首页 加入收藏

TOP

Word Cloud (词云) - R
2019-08-15 00:09:19 】 浏览:97
Tags:Word Cloud 词云



在前面已经陆续总结了如何用 Pythonjava script 创建词云了,今天要说的是 R。其实 SPSS 和 SAS 的 Word Cloud 扩展模板都是基于 R 实现的。


>> Create Word Cloud via R

1) 准备文本。

我们再…再次使用上次保存的 Word Cloud History.txt 的文本,这样我们就可以在最后比较用各种方法生成词云的效果。(好吧,其实主要是懒,继续用吧……)

2) 安装并加载所需的 R 包。

# 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() 函数来进行文本的大小写转换,清洗文本的空格符,常见停用词等。

# 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() 来查看矩阵数据。

#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。

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"))

Word Cloud R


>> Notes

如果要查看 wordcloud() 函数的各个参数的意义或者想给图形换个颜色,敲 help(wordcloud) 或者 help(RColorBrewer) 就可以查看帮助文档啦。


>> Sample Code

download here

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇R数据分析(一) 下一篇数据框筛选特定的子集

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目