将ngCMatrix强制为R中的dgCMatrix

时间:2015-08-20 02:26:34

标签: r sparse-matrix

我使用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)

1 个答案:

答案 0 :(得分:4)

事实证明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"