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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With