Creating a subset of words from a corpus in R

偶尔善良 提交于 2019-12-22 08:44:07

问题


I have a 1,500-row vector created from a Twitter search using the XML package. I have then converted it to a Corpus to be used with the tm package. I want to ultimately create a wordcloud with some (the most frequent) of those words, so I converted it to a TermDocumentMatrix to be able to find terms with a minimum frequency. I create the object "a", which is a list of those terms.

a <- findFreqTerms(mydata.dtm, 10)

The wordcloud package does not work on document matrices. So now, I want to filter the original vector to include only the words included in the "a" object (If I use the object itself, of course, I only have one instance of each of the frequent words).

Any suggestions are greatly appreciated.


回答1:


You can convert your tdm object into a matrix and work with that to get something that wordcloud can work with:

library(tm)
library(wordcloud)
# example data from the tm package
data(crude)
tdm <- TermDocumentMatrix(crude,
                      control = list(removePunctuation = TRUE,
                                     stopwords = TRUE))
v <- rowSums(as.matrix(tdm))
names(v) <- rownames(as.matrix(tdm))
v <- sort(v, decreasing=T)

Now with this you can filter out infrequent words with standard subsetting ([), or you can use the min.freq argument to wordcloud when you want to plot:

wordcloud(names(v), v, min.freq=10, scale=c(10,.3))



来源:https://stackoverflow.com/questions/15502802/creating-a-subset-of-words-from-a-corpus-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!