R:稀疏矩阵中的高效列减法

R: Efficient column subtraction in a sparse matrix

在这个稀疏矩阵中

library(Matrix)
m <- matrix(c(1,3,1,2,2,3,1,1,2,2,3,4,1,1,2,1,1,2), nrow = 6)
M <- sparseMatrix(i = m[,1], j = m[,2], x = m[,3], dimnames = list(expression(x1, x2, x3), expression(t1, t2, t3, t4)))
M
3 x 4 sparse Matrix of class "dgCMatrix"
   t1 t2 t3 t4
x1  1  2  .  .
x2  .  1  1  .
x3  1  .  .  2

如何最有效地从 t 处的值减去 t-1 处的值?

可以这样,将结果存入矩阵D:

D <- Matrix(0, nrow = 3, ncol = 4, dimnames = list(expression(x1, x2, x3), expression(t1, t2, t3, t4)))
for(i in 2:4){
    D[,i] <- M[,i]-M[,(i-1)]
}
D
3 x 4 sparse Matrix of class "dgCMatrix"
   t1 t2 t3 t4
x1  .  1 -2  .
x2  .  1  . -1
x3  . -1  .  2

但这是最​​有效的方法吗?

也许使用摘要 m 效率更高?

P.S.: D[2,3] 理想情况下会读作“0”而不是“.”。我怎样才能得到它?

可能有捷径,但一种方法是创建一个正确大小的空稀疏矩阵;

> D = Matrix(0, dim(M)[1], dim(M)[2], sparse=TRUE, dimnames=dimnames(M))

# 3 x 4 sparse Matrix of class "dgCMatrix"
#    t1 t2 t3 t4
# x1  .  .  .  .
# x2  .  .  .  .
# x3  .  .  .  .

...并用差值填充它;

> D[,2:ncol(D)] = M[,2:ncol(M)] - M[,1:ncol(M)-1]

# 3 x 4 sparse Matrix of class "dgCMatrix"
#    t1 t2 t3 t4
# x1  .  1 -2  .
# x2  .  1  . -1
# x3  . -1  .  2

另一种选择是cbind第一个空列:

empty_col_1 <- Matrix(0, nrow = nrow(M), ncol = 1, 
                      dimnames = list(NULL, "t1"))
D <- cbind(empty_col_1, M[, -1] - M[, -ncol(M)])