user4704857
user4704857

Reputation: 469

Update matrix using matrix of indices in R

I have a zero matrix with 5000 rows and 4000 columns. In addition, I have another matrix with 400,000 rows and 3 columns. The first column indicates to row index, the second column indicates to column index, and the last column is the value. I'd like to update the first matrix using the matrix of indices. For example:

data <- matrix(0, 10, 7)

> data
       [,1] [,2] [,3] [,4] [,5] [,6] [,7]
 [1,]    0    0    0    0    0    0    0
 [2,]    0    0    0    0    0    0    0
 [3,]    0    0    0    0    0    0    0
 [4,]    0    0    0    0    0    0    0
 [5,]    0    0    0    0    0    0    0
 [6,]    0    0    0    0    0    0    0
 [7,]    0    0    0    0    0    0    0
 [8,]    0    0    0    0    0    0    0
 [9,]    0    0    0    0    0    0    0
[10,]    0    0    0    0    0    0    0

ind <- matrix(c(1, 2, 5,
            2, 3, 6,
            5, 7, 4,
            5, 6, 16), ncol=3, byrow=T)

> ind
      [,1] [,2] [,3]
[1,]    1    2    5
[2,]    2    3    6
[3,]    5    7    4
[4,]    5    6   16

I'd like to get the below matrix after updating the elements:

> data
       [,1] [,2] [,3] [,4] [,5] [,6] [,7]
 [1,]    0    5    0    0    0    0    0
 [2,]    0    0    6    0    0    0    0
 [3,]    0    0    0    0    0    0    0
 [4,]    0    0    0    0    0    0    0
 [5,]    0    0    0    0    0    16   4
 [6,]    0    0    0    0    0    0    0
 [7,]    0    0    0    0    0    0    0
 [8,]    0    0    0    0    0    0    0
 [9,]    0    0    0    0    0    0    0
[10,]    0    0    0    0    0    0    0

what is the best/efficient solution in my big problem?

Upvotes: 6

Views: 1775

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

Since you can always use a two-column matrix for indexing, you can use the first two columns as the complete index then replace with the third column.

data[ind[, -3]] <- ind[, 3]

which results in

data
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,]    0    5    0    0    0    0    0
# [2,]    0    0    6    0    0    0    0
# [3,]    0    0    0    0    0    0    0
# [4,]    0    0    0    0    0    0    0
# [5,]    0    0    0    0    0   16    4
# [6,]    0    0    0    0    0    0    0
# [7,]    0    0    0    0    0    0    0
# [8,]    0    0    0    0    0    0    0
# [9,]    0    0    0    0    0    0    0
#[10,]    0    0    0    0    0    0    0

Upvotes: 9

Related Questions