首页 > 解决方案 > 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

谢谢 :)

标签: rdataframeterm-document-matrix

解决方案


编辑:重塑数据后:

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)

这不是你所期望的。我建议先重组你的数据: 在此处输入图像描述


推荐阅读