user5054
user5054

Reputation: 1096

How to set multiple matrix elements at a time in R?

I have a sparse representation of a matrix M as below:

1 3 6

2 5 7

5 4 10

which means that M[1,3]=6, M[2,5]=7, and M[5,4]=10. If I want to generate a regular 2D matrix from this representation, is there a way to set all existing elements of this 2D matrix M at once? I don't want to go over all index pairs in a loop, because there are thousands of such pairs (although there are only 3 of them in the example above).

I tried M[c(1,2,5),c(3,5,4)]=c(6,7,10), but it also sets M[1,5]=6 and M[1,4]=6 besides M[1,3]=6.

Upvotes: 1

Views: 161

Answers (1)

Roland
Roland

Reputation: 132736

You say "sparse" I say 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 you need a 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

Upvotes: 3

Related Questions