Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:稀疏矩阵中的有效列减法_R_Performance_Sparse Matrix_Subtraction - Fatal编程技术网

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)])