r - 有没有办法将词云返回为字符串或字符数据类型?
问题描述
我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
}
解决方案
您可以将语料库转换为 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.frame
andreshape2::melt()
步骤。
推荐阅读
- openoffice.org - 在 OpenOffice Calc 中使用键值列表
- excel - 在 Word 中从 VBA 打开 Excel
- javascript - 以 JSON 格式查看表格行详细信息中的内容
- swift - 在自定义表格视图单元格中设置 UIButton 的高度
- php - 检查复选框是否曾经有值 1
- c# - 如何将日期“20200415”格式化/转换为 2020-04-15?
- flutter - Flutter:DropdownButton 菜单在聚焦时不会自动打开
- selenium - 如何在不强制停止进程的情况下在 Selenium IDE 中处理多个下载?
- css - 通过内部标签选择外部元素
- node.js - 如何使用 Branchio 仅重定向 android+china 用户?