首页 > 解决方案 > 有没有办法将词云返回为字符串或字符数据类型?

问题描述

library(wordcloud)用来在 r 中制作词云。但是,我对作为字符串类型的实际单词更感兴趣,我以后可以在 excel 单元格中使用它。有什么方法可以让 r 中的 wordcloud 返回一个字符串,而不是创建一个 wordcloud 对象?

这是我的功能实现:

create_wordcloud <- function(text)  {
  corpus <- Corpus(VectorSource(text)
  w_cloud <- wordcloud(corpus, min.freq = 1,
            max.words=50, random.order=FALSE, rot.per=0.35, 
            colors=brewer.pal(8, "Dark2"))
  return(corpus) #I need this to be a string 
}

标签: rexceldataframeword-cloud

解决方案


您可以将语料库转换为 adata.frame并使用reshape2'melt()函数对其进行整形。

library(tm)
library(wordcloud)
library(reshape2)

create_wordcloud <- function(text)  {
    corpus <- Corpus(VectorSource(text)
    wordcloud(corpus, min.freq = 1,
        max.words=50, random.order=FALSE, rot.per=0.35, 
        colors=brewer.pal(8, "Dark2"))
    word_matrix <- as.matrix(DocumentTermMatrix(corpus))
    word_matrix_df <- as.data.frame(word_matrix)
    word_matrix_df <- melt(word_matrix_df, variable.name = 'word', value.name = 'frequency')

    return(word_matrix_df)
}

这将data.frame在其列中返回一个单词及其在文本中的频率。如果你对matrix结构没问题,你可以跳过data.frameandreshape2::melt()步骤。


推荐阅读