I have a 0-diagonal symmetric matrix X, such as
[1] [2] [3] [4] [5]
[1] 0.00000000 0.07065048 0.1019865 0.23641082 0.23641082
[2] 0.07065048 0.00000000 0.0000000 0.23641082 0.23641082
[3] 0.10198654 0.00000000 0.0000000 0.00000000 0.23641082
[4] 0.23641082 0.23641082 0.0000000 0.00000000 0.08870087
[5] 0.23641082 0.23641082 0.2364108 0.08870087 0.00000000
and I need to replace some of its elements with 0's according to a second matrix Y:
[1] [2]
[1] 3 2
[2] 4 3
[3] 1 2
So X[3,2], X[4,3], X[1,2] and, for symmetry's sake, X[2,3], X[3,4], X[2,1] should be replaced with zero's.
I came up with this solution:
for (i in 1:nrow(Y)) {
X[Y[i,1], Y[i,2]] <- 0
X[Y[i,2], Y[i,1]] <- 0
}
which is doing the trick, but I was wondering whether there is a better, more efficient way to code this using apply-like functions.
thank you very much for your attention.
This should work:
X[Y] <- 0
X[Y[, 2:1]] <- 0
or in one (balanced) statement:
X[rbind(Y[, 1:2],
Y[, 2:1])] <- 0
This form of indexing is commonly referred to as matrix indexing. Here is the relevant part from the ?"["
doc:
A third form of indexing is via a numeric matrix with the one column for each dimension: each row of the index matrix then selects a single element of the array, and the result is a vector. [...]
This will be faster than any type of loop, including *apply
functions.
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