After several hours of searching, I am turning to your expertise. Beginner in R, I try to speed up my code. My goal is to replace the values in a matrix A
. However,
It appears to me that you can simply do A[B[, 1:2]] <- 0
, by using the power of matrix indexing.
For example, A[cbind(1:4, 1:4)] <- 0
will replace A[1,1]
, A[2,2]
, A[3,3]
and A[4,4]
to 0. In fact, if A
has "dimnames" attributes (the "rownames" and "colnames" you refer to), we can also use the character strings as index.
Reproducible example
A <- matrix(1:16, 4, 4, dimnames = list(letters[1:4], LETTERS[1:4]))
# A B C D
#a 1 5 9 13
#b 2 6 10 14
#c 3 7 11 15
#d 4 8 12 16
set.seed(0); B <- cbind(sample(letters[1:4])), sample(LETTERS[1:4]))
# [,1] [,2]
#[1,] "d" "D"
#[2,] "a" "A"
#[3,] "c" "B"
#[4,] "b" "C"
## since `B` has just 2 columns, we can use `B` rather than `B[, 1:2]`
A[B] <- 0
# A B C D
#a 0 5 9 13
#b 2 6 0 14
#c 3 0 11 15
#d 4 8 12 0