我是R.的新手。我正在挖掘csv文件中的数据 - 一列中的报告摘要,另一列中的报告日期以及thrid列中的报告代理。我需要调查与“欺诈”相关的条款如何随着时间的推移发生变化或因代理商而异。我已经过滤了包含“欺诈”一词的行,并创建了一个新的csv文件。
如何创建一个术语freq矩阵,其中包含多年的行和术语作为列,以便我可以查找顶级freq术语并进行一些聚类?
基本上,我需要根据年份创建术语的术语频率矩阵
Input data: (csv)
**Year** **Summary** (around 300 words each)
1945 <text>
1985 <text>
2011 <text>
Desired 0utput : (Term frequency matrix)
term1 term2 term3 term4 .......
1945 3 5 7 8 .....
1985 1 2 0 7 .....
2011 . . .
Any help would be greatly appreciated.
答案 0 :(得分:4)
将来请提供一个最小的工作示例。
这不是完全使用tm而是使用qdap,因为它更适合您的数据类型:
library(qdap)
#create a fake data set (please do this in the future yourself)
dat <- data.frame(year=1945:(1945+10), summary=DATA$state)
## year summary
## 1 1945 Computer is fun. Not too fun.
## 2 1946 No it's not, it's dumb.
## 3 1947 What should we do?
## 4 1948 You liar, it stinks!
## 5 1949 I am telling the truth!
## 6 1950 How can we be certain?
## 7 1951 There is no way.
## 8 1952 I distrust you.
## 9 1953 What are you talking about?
## 10 1954 Shall we move on? Good then.
## 11 1955 I'm hungry. Let's eat. You already?
现在创建单词频率矩阵(类似于术语文档矩阵):
t(with(dat, wfm(summary, year)))
## about already am are be ... you
## 1945 0 0 0 0 0 0
## 1946 0 0 0 0 0 0
## 1947 0 0 0 0 0 0
## 1948 0 0 0 0 0 1
## 1949 0 0 1 0 0 0
## 1950 0 0 0 0 1 0
## 1951 0 0 0 0 0 0
## 1952 0 0 0 0 0 1
## 1953 1 0 0 1 0 1
## 1954 0 0 0 0 0 0
## 1955 0 1 0 0 0 1
或者你可以从qdap version 1.1.0创建一个tru DocumentTermMatrix:
with(dat, dtm(summary, year))
## > with(dat, dtm(summary, year))
## A document-term matrix (11 documents, 41 terms)
##
## Non-/sparse entries: 51/400
## Sparsity : 89%
## Maximal term length: 8
## Weighting : term frequency (tf)