【问题标题】:Concatenate dfm matrices in 'quanteda' package在“quanteda”包中连接 dfm 矩阵
【发布时间】:2016-05-21 13:41:12
【问题描述】:

是否存在一种方法可以同时连接两个包含不同列数和行数的 dfm 矩阵?它可以通过一些额外的编码来完成,所以我对临时代码不感兴趣,而是对通用且优雅的解决方案(如果有的话)感兴趣。

一个例子:

dfm1 <- dfm(c(doc1 = "This is one sample text sample."), verbose = FALSE)
dfm2 <- dfm(c(doc2 = "Surprise! This is one sample text sample."), verbose = FALSE)
rbind(dfm1, dfm2)

给出一个错误。

“tm”包可以直接连接其 dfm 矩阵;这对我来说太慢了。

还记得“quanteda”中的“dfm”是一个 S4 类。

【问题讨论】:

    标签: r sparse-matrix quanteda


    【解决方案1】:

    如果您使用的是最新版本,则应该“开箱即用”:

    packageVersion("quanteda")
    ## [1] ‘0.9.6.9’
    
    dfm1 <- dfm(c(doc1 = "This is one sample text sample."), verbose = FALSE)
    dfm2 <- dfm(c(doc2 = "Surprise! This is one sample text sample."), verbose = FALSE)
    
    rbind(dfm1, dfm2)
    ## Document-feature matrix of: 2 documents, 6 features.
    ## 2 x 6 sparse Matrix of class "dfmSparse"
    ##      is one sample surprise text this
    ## doc1  1   1      2        0    1    1
    ## doc2  1   1      2        1    1    1
    

    另见?selectFeatures,其中features 是一个dfm 对象(帮助文件中有示例)。

    添加

    请注意,这将正确对齐共同特征集中的两个文本,这与矩阵的普通rbind 方法不同,其列必须匹配。出于同样的原因,rbind() 实际上不适用于具有不同术语的 DocumentTermMatrix 对象的 tm 包:

    require(tm)
    dtm1 <- DocumentTermMatrix(Corpus(VectorSource(c(doc1 = "This is one sample text sample."))))
    dtm2 <- DocumentTermMatrix(Corpus(VectorSource(c(doc2 = "Surprise! This is one sample text sample."))))
    rbind(dtm1, dtm2)
    ## Error in f(init, x[[i]]) : Numbers of columns of matrices must match.
    

    这几乎明白了,但似乎重复了重复的功能:

    as.matrix(rbind(c(dtm1, dtm2)))
    ##     Terms
    ## Docs one sample sample. text this surprise!
    ##    1   1      1       1    1    1         0
    ##    1   1      1       1    1    1         1
    

    【讨论】:

    • 谢谢!它简化了代码,一个非常有用的选项。
    • 当使用 'tm' 时,你应该参考函数 'c' 的调度。这个包使用它自己的代码来执行这种特殊的绑定。 “base R”本身不能做到这一点(因为 'rbind 的限制)。所以c(dtm1, dtm2) 会正常工作。顺便说一句,据我所知,'tm' DFM 可以直接从'quanteda' DFM 创建,但反之则不然。
    猜你喜欢
    • 2017-05-26
    • 2022-01-20
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多