替换由另一个矩阵索引的矩阵元素 [英] Replacing matrix elements indexed by another matrix
问题描述
经过几个小时的搜索,我将转向您的专业知识. R的初学者,我尝试加快我的代码的速度.我的目标是替换矩阵A
中的值.但是,我想替换基于另一个矩阵B
的两个向量的值. B[, 1]
是矩阵A
的行i
的名称.第二列B[, 2]
对应于矩阵A
的列名称.
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, I want to replace values based on two vectors of another matrix B
. B[, 1]
is the name of row i
of the matrix A
. The second column, B[, 2]
corresponds to the name of column of the matrix A
.
我的代码的第一个版本是在循环中使用match函数.
The first version of my code was to use the match function in a loop.
for(k in 1:L){
i <- B[k,1]
j <- B[k,2]
d <- match(i,rownames(A))
e <- match(j,colnames(A))
A[d, e] <- 0
}
第二个版本允许我加快一点速度
The second version allowed me to speed a little bit:
for( k in 1:L) {
A[match(B[k,1],rownames(A)), match(B[k,2],colnames(A))] <- 0
}
但是,处理时间太长或太长.所以我想使用apply
函数.为此,我必须在B
的每个行向量中使用apply
.
However, the processing time is long, too long. So I thought to use the apply
function. For this, I have to use apply
in each row vectors of B
.
使用apply
功能是否有效?还是我走错路了?
Is Using apply
function a great way? Or I am going in the wrong way?
推荐答案
在我看来,您可以通过使用矩阵索引的强大功能来简单地进行A[B[, 1:2]] <- 0
.
It appears to me that you can simply do A[B[, 1:2]] <- 0
, by using the power of matrix indexing.
例如,A[cbind(1:4, 1:4)] <- 0
会将A[1,1]
,A[2,2]
,A[3,3]
和A[4,4]
替换为0.实际上,如果A
具有假名"属性(行名"和同名"您指的是),我们也可以使用字符串作为索引.
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.
可复制的示例
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
这篇关于替换由另一个矩阵索引的矩阵元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!