Reputation: 3138
I have a 3-dimensional array arr
where each array element is a matrix with the same number of rows and columns. Then I have a 3-column matrix m
where the first two columns specify an index (row and column) and the last column a value.
arr = array(0, dim = c(2, 2, 3))
m = matrix(c(1, 2, -100, 2, 1, -99), ncol = 3, byrow = TRUE)
colnames(m) = c("row_index", "column_index", "value")
Now I want to fill in this value at the specified indexes for each of the array elements. I couldn't find a better way to do this than the following lines of code, but I would prefer a solution with less code repetition. What's the best way to do this?
arr[, , 1][m[, 1:2]] = m[, 3]
arr[, , 2][m[, 1:2]] = m[, 3]
arr[, , 3][m[, 1:2]] = m[, 3]
Upvotes: 3
Views: 742
Reputation: 70266
How about this apply approach:
arr[] <- apply(arr, 3, FUN = function(x) {x[m[,1:2]] <- m[,3]; x})
arr
# , , 1
#
# [,1] [,2]
# [1,] 0 -100
# [2,] -99 0
#
# , , 2
#
# [,1] [,2]
# [1,] 0 -100
# [2,] -99 0
#
# , , 3
#
# [,1] [,2]
# [1,] 0 -100
# [2,] -99 0
Upvotes: 4