在这个稀疏矩阵中
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”而不是“.”。我怎样才能获得它?
最佳答案
另一个选项是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)])
关于R:稀疏矩阵中的高效列减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36007501/