将 ngCMatrix 强制为 R 中的 dgCMatrix

coerce ngCMatrix as dgCMatrix in R

我正在使用 sparseMatrix 将组从属关系数据转换为社交图(双模式到单模式,as explained here),但我不确定:如何将稀疏模式矩阵对象强制转换为稀疏整数矩阵?

library(data.table)
library(Matrix)
dt <- data.table(person = c('Sam','Sam','Sam','Greg','Tom','Tom','Tom','Mary','Mary'), 
                 group = c('a','b','e','a','b','c','d','b','d'))

# non-sparse, desirable output
M <- as.matrix(table(dt))
M %*% t(M)

# sparse, binary instead of integer 
rows <- sort(unique(dt$person))
cols <- sort(unique(dt$group))
dimnamesM <- list(person = rows, groups = cols)
sprsM <- sparseMatrix(i = match(dt$person, rows), 
                      j = match(dt$group, cols), dimnames = dimnamesM)
sprsM %*% t(sprsM)

原来sprsM <- as(sprsM, "dgCMatrix")做到了。有关详细信息,请参阅 here

sprsM <- sparseMatrix(i = match(dt$person, rows), 
                      j = match(dt$group, cols), dimnames = dimnamesM)
sprsM
# 4 x 5 sparse Matrix of class "ngCMatrix"
#       groups
# person a b c d e
#   Greg | . . . .
#   Mary . | . | .
#   Sam  | | . . |
#   Tom  . | | | .

class(sprsM)
# [1] "ngCMatrix"
# attr(,"package")
# [1] "Matrix"

sprsM <- as(sprsM, "dgCMatrix")
sprsM
# 4 x 5 sparse Matrix of class "dgCMatrix"
#       groups
# person a b c d e
#   Greg 1 . . . .
#   Mary . 1 . 1 .
#   Sam  1 1 . . 1
#   Tom  . 1 1 1 .

class(sprsM)
# [1] "dgCMatrix"
# attr(,"package")
# [1] "Matrix"