Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update matrix using matrix of indices in R

Tags:

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?

like image 320
user4704857 Avatar asked Sep 12 '15 22:09

user4704857


1 Answers

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
like image 122
Rich Scriven Avatar answered Sep 29 '22 08:09

Rich Scriven