【问题标题】:How to convert Data Frame to Term Document Matrix in R?如何将数据框转换为 R 中的术语文档矩阵?
【发布时间】:2018-06-24 02:24:14
【问题描述】:

我有一个表(数据框)myTable,单列如下:

         sentence
1      it is a window
2      My name is john doe
3      Thank you
4      Good luck
.
.
.

我想将它转换为 R 中的术语文档矩阵。我这样做了:

tdm_s <- TermDocumentMatrix(Corpus(DataframeSource(myTable)))

但我收到了这个错误:

Error: all(!is.na(match(c("doc_id", "text"), names(x)))) is not TRUE

我用谷歌搜索并找不到任何东西。如何进行这种转换?

【问题讨论】:

  • DataframeSource() 期望什么样的输入? myTable 是那种类型的吗?
  • myTabledataframe。此外,我将Corpus(DataframeSource(myTable)) 传递给TermDocumentMatrix(),而不是myTable。 @AkselA
  • 当然,但是什么样的data.frame。以及错误发生在什么函数上,是继承的吗?
  • 当我运行这个DataframeSource(myTable) 时,会发生错误。 @AkselA

标签: r dataframe type-conversion tf-idf


【解决方案1】:

您需要执行以下操作才能转换为术语文档矩阵:

## Your sample data
myTable <- data.frame(sentence = c("it is a window", "My name is john doe", "Thank you", "Good luck"))

## You need to use VectorSource before using Corpus
library(tm)
myCorpus <- Corpus(VectorSource(myTable$sentence))
tdm <- TermDocumentMatrix(myCorpus)

inspect(tdm)
#<<TermDocumentMatrix (terms: 8, documents: 4)>>
#Non-/sparse entries: 8/24
#Sparsity           : 75%
#Maximal term length: 6
#Weighting          : term frequency (tf)
#Sample             :
#         Docs
#Terms   1 2 3 4
#doe     0 1 0 0
#good    0 0 0 1
#john    0 1 0 0
#luck    0 0 0 1
#name    0 1 0 0
#thank   0 0 1 0
#window  1 0 0 0
#you     0 0 1 0

【讨论】:

  • 这可能是因为您使用的是DataframeSource 而不是VectorSource。由于错误表明doc_iddoc 的匹配不是非NA。当您使用 DataframeSource 时,我猜测 id 和空文档会导致问题。
  • @Patris:我试着轻轻地暗示它,但请阅读the documentation。它有答案。
【解决方案2】:

如果您不介意使用 Quanteda 软件包(非常好)...

require(quanteda)
# Your sample data 
# Important to make sure the sentence variable is not converted to type factor
myTable <- data.frame(sentence = c("it is a window", "My name is john doe", "Thank you", "Good luck"),
                  stringsAsFactors = FALSE)
newcorpus <- corpus(myTable, text_field = "sentence") # you have to tell it the name of the text field
# lots of options to dfm read the help pages
newdfm <- dfm(newcorpus, remove_punct = TRUE, remove = stopwords("english"), stem = TRUE)
newdfm

【讨论】:

    猜你喜欢
    • 2017-10-16
    • 1970-01-01
    • 2021-07-27
    • 2018-05-04
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    相关资源
    最近更新 更多