R 如何使两个稀疏矩阵的列相等

R 如何使两个稀疏矩阵的列相等,r,sparse-matrix,R,Sparse Matrix,我有两个稀疏矩阵,用于一个训练集和测试集,我需要删除每个矩阵中不在另一个矩阵中的列-使两个矩阵中的列相同。目前,我正在使用循环进行此操作,但我相信有一种更有效的方法: # take out features in training set that are not in test i<-0 for(feature in testmatrix@Dimnames[2][[1]]){ i<-i+1 if(!(feature %in% trainmatrix@Dimn

我有两个稀疏矩阵,用于一个训练集和测试集,我需要删除每个矩阵中不在另一个矩阵中的列-使两个矩阵中的列相同。目前,我正在使用循环进行此操作,但我相信有一种更有效的方法:

# take out features in training set that are not in test
  i<-0
  for(feature in testmatrix@Dimnames[2][[1]]){
    i<-i+1
    if(!(feature %in% trainmatrix@Dimnames[2][[1]])){
      removerows<-c(removerows, i)
    }
  }
  testmatrix<-testmatrix[,-removerows]

# and vice versa...
#取出培训集中未在测试中的功能

在我看来,您所要做的就是保留
testmatrix
的列,这些列也出现在
trainmatrix
中,反之亦然。由于要将其应用于两个矩阵,一种快速的方法是对每个矩阵的
colnames
向量使用
intersect
,以找到相交的
colnames
,然后使用它来子集:

#  keep will be a vector of colnames that appear in BOTH train and test matrices
keep <- intersect( colnames(test) , colnames(train) )

#  Then subset on this vector
testmatrix <- testmatrix[ , keep ]
trainmatrix <- trainmatrix[ , keep ]
keep是列和测试矩阵中出现的列名向量
如果我们有
testmatrix
trainmatrix
…这是使用矩阵中的sparse.model.matrix()创建的dgCMatrix类型,那么它将更容易提供帮助library@pablomo因此,上面的方法似乎可以正常工作,因为您可以使用“colnames”