R:稀疏矩阵中的有效列减法
在这个稀疏矩阵中R:稀疏矩阵中的有效列减法,r,performance,sparse-matrix,subtraction,R,Performance,Sparse Matrix,Subtraction,在这个稀疏矩阵中 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 "dgCMa
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
库(矩阵)
m可能有捷径,但一种方法是创建一个正确大小的空稀疏矩阵
> 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)])
empty\u col\u 1更好,你得到了我在作业中丢失的0
:)仍然是R初学者,cbind
看起来很有用。感谢Dmitry和Joachim,你的解决方案比我的循环快8倍。可以,只要有人想出更好的解决方案就行了。
empty_col_1 <- Matrix(0, nrow = nrow(M), ncol = 1,
dimnames = list(NULL, "t1"))
D <- cbind(empty_col_1, M[, -1] - M[, -ncol(M)])