在 R 中使用 "termFreq" 函数时出错

Error in using "termFreq" function in R

我使用tm 包在R 中构建了一个语料库。我想改变频率边界,只保留在整个文档中至少重复 4 次的单词。之后,我需要根据这些术语构建文档术语矩阵。

'Data' 是一个 45k x 2 矩阵。第一列是 'Text',每行平均包含 10 个单词。第二列是 'Code',每行包含一个 5 位代码。

'Text' 中将近 15k 个单词重复了一两次。我想删除它们然后构建文档术语矩阵。

这是我试过的代码:

MyCorpus <- Corpus(VectorSource(Data$Text))
MyCorpus <- tm_map(MyCorpus , removeWords, stopwords('english'))
MyCorpus  <- tm_map(MyCorpus , stripWhitespace)
MyCorpus  <- termFreq(MyCorpus  , control = list(local = c(4, Inf)))

但是我在第 4 行遇到了这个错误:

错误:inherits(doc, "TextDocument") 不正确

我该怎么办?

termFreq 用于文档,而不是语料库。如果您想在构建 DocumentTermMatrix 时过滤频率,请使用 DocumentTermMatrix 函数

DTM  <- DocumentTermMatrix(MyCorpus  , control = list(bounds=list(global = c(4, Inf))))

这是一个例子...

library(tm)

Data<-data.frame(Text=c("aaa bbb aaa ddd","bbb aaa aaa bbb ccc","bbb aaa aaa bbb ddd", "aaa bbb ddd"))

MyCorpus <- Corpus(VectorSource(Data$Text))
MyCorpus <- tm_map(MyCorpus , removeWords, stopwords('english'))
MyCorpus  <- tm_map(MyCorpus , stripWhitespace)
DTM  <- DocumentTermMatrix(MyCorpus , control = list(bounds = list(global=c(2, Inf))))

inspect(DTM)

# <<DocumentTermMatrix (documents: 4, terms: 3)>>
# Non-/sparse entries: 11/1
# Sparsity           : 8%
# Maximal term length: 3
# Weighting          : term frequency (tf)

#     Terms
# Docs aaa bbb ddd
#    1   2   1   1
#    2   2   2   0
#    3   2   2   1
#    4   1   1   1

这里我们使用全局边界来确保我们只保留出现在至少两个文档中的单词。您还可以设置本地绑定以要求单词在每个文档中出现一定次数。