如何在Quanteda中添加/减去文档项矩阵?

时间:2019-05-19 02:06:26

标签: r sparse-matrix quanteda

考虑这个简单的例子

dfm1 <- tibble(text = c('hello world',
                         'hello quanteda')) %>% 
  corpus() %>% tokens() %>% dfm()
> dfm1
Document-feature matrix of: 2 documents, 3 features (33.3% sparse).
2 x 3 sparse Matrix of class "dfm"
       features
docs    hello world quanteda
  text1     1     1        0
  text2     1     0        1

dfm2 <- tibble(text = c('hello world',
                        'good nigth quanteda')) %>% 
  corpus() %>% tokens() %>% dfm()
Document-feature matrix of: 2 documents, 5 features (50.0% sparse).
2 x 5 sparse Matrix of class "dfm"
       features
docs    hello world good nigth quanteda
  text1     1     1    0     0        0
  text2     0     0    1     1        1

如您所见,dfmstext1这两个text2中具有相同的文本标识符。

我想将dfm2“减”到dfm1,以便将dfm1中的每个条目都减去到dfm2中的(可能)匹配条目中(相同的文本,相同的单词)

例如,在text1中,hello发生1次,在text2中也发生1次。因此,该条目的输出应为0(即1-1)。当然,不在两个dfms中的条目应保持不变。

如何在Quanteda中做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用dfm_match()将dfm的功能集与另一个dfm的功能集进行匹配。我还整理了您的代码,因为对于这个简短的示例,您的某些管道可以简化。

library("quanteda")
## Package version: 1.4.3
## Parallel computing: 2 of 12 threads used.
## See https://quanteda.io for tutorials and examples.

dfm1 <- dfm(c("hello world", "hello quanteda"))
dfm2 <- dfm(c("hello world", "good night quanteda"))

as.dfm(dfm1 - dfm_match(dfm2, features = featnames(dfm1)))
## Document-feature matrix of: 2 documents, 3 features (33.3% sparse).
## 2 x 3 sparse Matrix of class "dfm"
##        features
## docs    hello world quanteda
##   text1     0     0        0
##   text2     1     0        0

as.dfm()来自以下事实:+运算符是为父稀疏 Matrix 类定义的,而不是专门为 quanteda dfm定义的,因此它会删除dfm的类,并将其转换为dgCMatrix。使用as.dfm()将其强制返回到dfm可以解决该问题,但是它将删除dfm对象(例如docvars)的原始属性。