Replacing matrix elements indexed by another matrix

余生颓废 提交于 2019-12-01 23:11:54

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!