这表明需要weight
为 dfm-class 的方法添加一个选项,以使其更容易,更重要的是不要从稀疏矩阵中剥离 dfm 的类。dfm 在对象中还有一个@weights
槽,旨在记录其加权方式,因此也可以/应该保留此信息。
@lukeA 的解决方案两次删除 dfm 类(不是他或你的错,而是我的错!!),一次%*%
在<-
. 第一个可以通过使用按列回收和标准*
而不是矩阵乘法来避免%*%
,因为我认为没有为 dfm-class for 编写方法%*%
(这就是它默认为该sparseMatrix
方法的原因)。如果您重新分配子矩阵元素,则当前无法避免第二种情况,但如果您只需将一个 dfm 类对象对象替换为另一个对象,则可以避免这种情况。
要以保留类的方式创建新的 dfm-class 对象,这将起作用(在这里,我通过添加第二个文档和另一个功能使问题变得更加复杂):
str <- c("apple is better than banana", "banana banana apple much better")
weights <- c(apple = 5, banana = 3, much = 0.5)
mydfm <- dfm(str, ignoredFeatures = stopwords("english"), verbose = FALSE)
# use name matching for indexing, sorts too, returns NA where no match is found
newweights <- weights[features(mydfm)]
# reassign 1 to non-matched NAs
newweights[is.na(newweights)] <- 1
# works because of column-wise recycling of the vector
mydfm * newweights
## Document-feature matrix of: 2 documents, 4 features.
## 2 x 4 sparse Matrix of class "dfmSparse"
## features
## docs apple better banana much
## text1 5 3.0 5 0
## text2 1 0.5 2 0.5
还有一点需要注意:我鼓励使用 dfm-class-specific 方法来提取列名之类的东西,例如,features(mydfm)
而不是colnames(mydfm)
,即使这些可能保持等效。