Reputation: 8117
I have a matrix
myMatrix <- matrix(data = 0, nrow = 4, ncol = 4)
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 0 0 0 0
[3,] 0 0 0 0
[4,] 0 0 0 0
and I want to change particular values
myMatrix[1,1] <- 1
myMatrix[2,3] <- 1
myMatrix[4,4] <- 1
myMatrix
[,1] [,2] [,3] [,4]
[1,] 1 0 0 0
[2,] 0 0 1 0
[3,] 0 0 0 0
[4,] 0 0 0 1
How can I do this efficient/elegantly if I have two vectors containing the row and column indexes:
rowIndexes <- c(1,2,4)
colIndexes <- c(1,3,4)
The assigned value is constant (in this case 1
).
I know how to do it with a for
-loop, but this feels inefficient.
Upvotes: 3
Views: 811
Reputation: 887048
We can cbind
the row/column index, subset the myMatrix
and assign values to 1
myMatrix[cbind(rowIndexes, colIndexes)] <- 1
myMatrix
# [,1] [,2] [,3] [,4]
#[1,] 1 0 0 0
#[2,] 0 0 1 0
#[3,] 0 0 0 0
#[4,] 0 0 0 1
Upvotes: 4