代码之家  ›  专栏  ›  技术社区  ›  km5041

R: 将文档项计数的数据框转换为文档项矩阵(dtm)

  •  0
  • km5041  · 技术社区  · 7 年前

    我已经有了一个文档术语计数级别的数据框架,注意到文档和术语只是通过整数索引,分数是加权连续数,如果这是相关的,例如:

    doc  term  count
    1    2     2
    1    5     3.1
    2    2     0.4
    3    5     5.9
    

    但它目前是一个数据帧,我想将其转换为dtm格式,以便使用一些dtm就绪的函数(即RNewsflow的“documents.compare”函数)。

    我一直在尝试通过以下方式使用“cast\u dtm”:

    dtm <- as.matrix(df) %>% cast_dtm(document, term, count)
    

    其中,“df”是上面示例的数据帧,但我得到以下错误:

    Error in UseMethod("ungroup") : no applicable method for 'ungroup' applied to an object of class "c('matrix', 'double', 'numeric')"
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   phiver    7 年前

    你就快到了。您需要输入“doc”,而不是“document”,因为您的列名是doc而不是document。请参见下面的示例。

    library(tidytext)
    library(dplyr)
    dtm <- df %>% cast_dtm(document = doc, term = term, value = count)
    

    数据:

    df <- structure(
      list(
        doc = c(1L, 1L, 2L, 3L),
        term = c(2L, 5L, 2L,5L),
        count = c(2, 3.1, 0.4, 5.9)),
      .Names = c("doc", "term", "count"),
      class = "data.frame",
      row.names = c(NA,-4L)
    )