r - R将数据框转换为术语文档矩阵
问题描述
我目前正在学习围绕 R 的方法,并且我对以下问题感到困扰:
我有一个像这样构建的数据框
word freq1 freq2
tree 10 20
this 2 3
that 4 5
...
它显示了单词在文本 1 (freq1) 和文本 2 (freq2) 中的使用频率。是否可以将其转换为术语文档矩阵?我需要它是一个术语文档矩阵来应用以下功能
par(mfrow=c(1,1))
comparison.cloud(tdm, random.order=FALSE, colors =
c("indianred3","lightsteelblue3"),
title.size=2.5, max.words=400)
来自https://rpubs.com/brandonkopp/creating-word-clouds-in-r
谢谢 :)
解决方案
编辑:重塑数据后:
library(reshape2)
library(tm)
library(dplyr)
library(wordcloud)
df2<-df %>%
gather("Origin","Freq",c(2,3)) %>%
acast(word~Origin,fill=0,value.var = "Freq")
comparison.cloud(df2, random.order=FALSE, colors = c("indianred3","lightsteelblue3"),
max.words=400)
原始答案: 您的数据有问题。这是通向 wordcloud 或比较云的基本工作流程。
library(tm)
library(dplyr)
library(wordcloud)
df<-read.table(text="word freq1 freq2
Tree 10 20
This 2 3
That 4 5",header=T)
df$word<-as.character(df$word)
df1<-df %>%
gather()
corpus_my<-Corpus(VectorSource(df1))
tdm<-as.matrix(TermDocumentMatrix(corpus_my))
comparison.cloud(tdm, random.order=FALSE, colors = c("indianred3","lightsteelblue3"),
max.words=400)
推荐阅读
- .net - 如何修复 net::ERR_HTTP2_PROTOCOL_ERROR
- r - 每次 id1 在 id3 的字符串中时,将 id2 部分放在新列中
- java - 使用 Sparklauncher 调用 Spring Boot 应用程序的特定服务类或控制器方法
- scala - 在 Shapeless 中添加两个以上的联产品
- ssh - ssh 今天不会使用公钥登录(!) - 调试会给出奇怪的输出
- python - 将 robots.txt 中的多个用户代理与 Scrapy 匹配
- php - 如何在包含 include('xyz.php') 的目录中包含 php 文件;从另一个目录?
- eclipse - Eclipse Text Editor 背景颜色似乎被当前主题覆盖
- bash - 如何使用 Apple Script 关闭终端窗口
- python - 我可以按下混淆矩阵中的一个单元格从而打开一个文件吗?