我有以下[10 x 10]稀疏矩阵:
library(Matrix)
m = as(diag(10), 'sparseMatrix')
m
10 x 10 sparse Matrix of class "dgCMatrix"
[1,] 1 . . . . . . . . .
[2,] . 1 . . . . . . . .
[3,] . . 1 . . . . . . .
[4,] . . . 1 . . . . . .
[5,] . . . . 1 . . . . .
[6,] . . . . . 1 . . . .
[7,] . . . . . . 1 . . .
[8,] . . . . . . . 1 . .
[9,] . . . . . . . . 1 .
[10,] . . . . . . . . . 1
如果我对此进行简单算术,它现在会存储所有零。
M = m + 1 - 1
M
10 x 10 Matrix of class "dgeMatrix"
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 0 0 0 0 0 0 0 0 0
[2,] 0 1 0 0 0 0 0 0 0 0
[3,] 0 0 1 0 0 0 0 0 0 0
[4,] 0 0 0 1 0 0 0 0 0 0
[5,] 0 0 0 0 1 0 0 0 0 0
[6,] 0 0 0 0 0 1 0 0 0 0
[7,] 0 0 0 0 0 0 1 0 0 0
[8,] 0 0 0 0 0 0 0 1 0 0
[9,] 0 0 0 0 0 0 0 0 1 0
[10,] 0 0 0 0 0 0 0 0 0 1
我知道我可以使这个新矩阵稀疏,但有没有办法让R自动执行此操作?
M = as(M, 'sparseMatrix')
答案 0 :(得分:4)
它将m+1-1
计算为(m+1)-1
且m+1
不稀疏,因此从那时起您就不会有稀疏矩阵。
尝试m+(1-1)
。