如何将数据框转换为 DocumentTermMatrix?

How to cast a dataframe to a DocumentTermMatrix?

我正在尝试使用 tidytext 将一小段词频转换为 DocumentTermMatrix,但该函数似乎没有按预期工作。我从 AssociatedPress 开始,我知道它是一个 documentTermMatrix,整理并将其投回,但输出与原始矩阵不同。我做错了什么?

library(topicmodels)
data(AssociatedPress)
ap_td <- tidy(AssociatedPress)
tt <- ap_td %>%
  cast_dtm(document, term, count)

当我转换 ap_td 时,元素 $Docs 不是 NULL,但在 AssociatedPress 中它是 NULL: 海峡(TT)

List of 6
 $ i       : int [1:302031] 1 16 35 72 84 93 101 111 155 161 ...
 $ j       : int [1:302031] 1 1 1 1 1 1 1 1 1 1 ...
 $ v       : num [1:302031] 1 1 1 1 1 1 1 1 1 1 ...
 $ nrow    : int 2246
 $ ncol    : int 10473
 $ dimnames:List of 2
  ..$ Docs : chr [1:2246] "1" "2" "3" "4" ...
  ..$ Terms: chr [1:10473] "adding" "adult" "ago" "alcohol" ...
 - attr(*, "class")= chr [1:2] "DocumentTermMatrix" "simple_triplet_matrix"
 - attr(*, "weighting")= chr [1:2] "term frequency" "tf"

List of 6
 $ i       : int [1:302031] 1 1 1 1 1 1 1 1 1 1 ...
 $ j       : int [1:302031] 116 153 218 272 299 302 447 455 548 597 ...
 $ v       : num [1:302031] 1 2 1 1 1 1 2 1 1 1 ...
 $ nrow    : int 2246
 $ ncol    : int 10473
 $ dimnames:List of 2
  ..$ Docs : NULL
  ..$ Terms: chr [1:10473] "aaron" "abandon" "abandoned" "abandoning" ...
 - attr(*, "class")= chr [1:2] "DocumentTermMatrix" "simple_triplet_matrix"
 - attr(*, "weighting")= chr [1:2] "term frequency" "tf"

cast_dtm 检索警告

Warning message: Trying to compute distinct() for variables not found in the data: - row_col, column_col This is an error, but only a warning is raised for compatibility reasons. The operation will return the input unchanged.

在 GitHub 上,我发现 this issue 现在应该已经修复了。

我没有收到你使用 tidytext 0.1.9.900 和 R 3.5.0 的警告消息。

对于术语、行和列的数量,dtm 是相同的。而且所有的计数都是正确的。

区别确实在于tt$dimnames$DocsAssociatedPress$dimnames$Docs的$dimnames$Docs之间。

这样做的原因是,如果像 AssociatedPress 那样在整理之前 dtm 中没有 docid,则整理函数会将 AssociatedPress$i 分配给 tidy_text 中的文档变量(ap_td).将其转换回 dtm,将使用 tidy_text data.frame (ap_td) 中的文档值填充 $dimnames$Docs。所以最终 AssociatedPress$i 值将以 tt$dimnames$Docs 结束。

你可以看到,如果你将美联社的 $i 与 tt 的 Docs 进行比较。

all.equal(unique(as.character(AssociatedPress$i)), unique(tt$dimnames$Docs))
[1] TRUE

或从 AssociatedPress 比较到 ap_td 到 tt:

all.equal(unique(as.character(AssociatedPress$i)), unique(tt$dimnames$Docs), unique(ap_td))
[1] TRUE

如果您想自己遵循逻辑,可以检查所有使用的函数on the github page for the sparse_tidiers。从 tidy.DocumentTermMatrix 开始,然后跟随函数调用到 tidy.simple_triplet_matrix,最后到 tidy_triplet