将DocumentTermMatrix转换为数据框
我手头有一个来自 topicmodels 包、在 R: 中的 AssociatedPress tibble。
data("AssociatedPress", package = "topicmodels")
我得到的是:
> AssociatedPress
<<DocumentTermMatrix (documents: 2246, terms: 10473)>>
Non-/sparse entries: 302031/23220327
Sparsity : 99%
Maximal term length: 18
Weighting : term frequency (tf)
我想把它转换成一个按词频加权的文档-词项矩阵。
我尝试在 tibble 包中使用 as_data_frame,但它提示已弃用,所以我应该尝试as.data.frame(base R)吗?有什么建议?
>tibble::as_data_frame(AssociatedPress)
Error in as.data.frame.default(value, stringsAsFactors = FALSE) :
cannot coerce class ‘c("DocumentTermMatrix", "simple_triplet_matrix")’ to a data.frame
In addition: Warning message:
`as_data_frame()` was deprecated in tibble 2.0.0.
ℹ Please use `as_tibble()` (with slightly different semantics) to convert to a
tibble, or `as.data.frame()` to convert to a data frame.
as.data.frame(AssociatedPress)
Error in as.data.frame.default(AssociatedPress) :
cannot coerce class ‘c("DocumentTermMatrix", "simple_triplet_matrix")’ to a data.fra
解决方案
我们可以使用 tidytext::tidy() 函数:
data("AssociatedPress", package = "topicmodels")
tidytext::tidy(AssociatedPress)
#> # A tibble: 302,031 × 3
#> document term count
#> <int> <chr> <dbl>
#> 1 1 adding 1
#> 2 1 adult 2
#> 3 1 ago 1
#> 4 1 alcohol 1
#> 5 1 allegedly 1
#> 6 1 allen 1
#> 7 1 apparently 2
#> 8 1 appeared 1
#> 9 1 arrested 1
#> 10 1 assault 1
#> # ℹ 302,021 more rows
创建于2026-05-11,使用 reprex v2.1.1
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。