问题描述
经过几个小时的搜索,我开始求助于您的专业知识.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
code> 有dimnames"属性(你所指的rownames"和colnames"),我们也可以使用字符串作为索引.
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
这篇关于替换由另一个矩阵索引的矩阵元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!