【问题标题】:Is there a way to return word cloud into string or character data type?有没有办法将词云返回为字符串或字符数据类型?
【发布时间】:2023-03-08 21:25:01
【问题描述】:

我正在使用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 
}

【问题讨论】:

  • 您能提供一些示例数据和所需的输出吗?

标签: r excel dataframe word-cloud


【解决方案1】:

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

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.framereshape2::melt() 步骤。

【讨论】:

    猜你喜欢
    • 2022-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2021-06-20
    • 2020-02-28
    • 1970-01-01
    相关资源
    最近更新 更多