How to set multiple matrix elements at a time in R? -
i have sparse representation of matrix m below:
1 3 6 2 5 7 5 4 10
which means m[1,3]=6
, m[2,5]=7
, , m[5,4]=10
. if want generate regular 2d matrix representation, there way set existing elements of 2d matrix m @ once? don't want go on index pairs in loop, because there thousands of such pairs (although there 3 of them in example above).
i tried m[c(1,2,5),c(3,5,4)]=c(6,7,10)
, sets m[1,5]=6
, m[1,4]=6
besides m[1,3]=6
.
you "sparse" matrix:
library(matrix) m <- sparsematrix(i = c(1, 2, 5), j = c(3, 5, 4), x = c(6, 7, 10), dims = c(5, 5)) #5 x 5 sparse matrix of class "dgcmatrix" # #[1,] . . 6 . . #[2,] . . . . 7 #[3,] . . . . . #[4,] . . . . . #[5,] . . . 10 .
if need base r matrix:
as.matrix(m) # [,1] [,2] [,3] [,4] [,5] #[1,] 0 0 6 0 0 #[2,] 0 0 0 0 7 #[3,] 0 0 0 0 0 #[4,] 0 0 0 0 0 #[5,] 0 0 0 10 0
Comments
Post a Comment