[英]Replacing matrix elements indexed by another matrix
After several hours of searching, I am turning to your expertise.经过几个小时的搜索,我转向您的专业知识。 Beginner in R, I try to speed up my code.
R 初学者,我尝试加速我的代码。 My goal is to replace the values in a matrix
A
.我的目标是替换矩阵
A
的值。 However, I want to replace values based on two vectors of another matrix B
.但是,我想替换基于另一个矩阵
B
两个向量的值。 B[, 1]
is the name of row i
of the matrix A
. B[, 1]
是矩阵A
的第i
行的名称。 The second column, B[, 2]
corresponds to the name of column of the matrix A
.第二列
B[, 2]
对应于矩阵A
的列名。
The first version of my code was to use the match function in a loop.我的代码的第一个版本是在循环中使用 match 函数。
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
}
However, the processing time is long, too long.但是,处理时间很长,太长了。 So I thought to use the
apply
function.所以我想使用
apply
函数。 For this, I have to use apply
in each row vectors of B
.为此,我必须在
B
每一行向量中使用apply
。
Is Using apply
function a great way?使用
apply
函数是个好方法吗? Or I am going in the wrong way?还是我走错路了?
It appears to me that you can simply do A[B[, 1:2]] <- 0
, by using the power of matrix indexing.在我看来,你可以简单地做
A[B[, 1:2]] <- 0
,通过使用矩阵索引的力量。
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[cbind(1:4, 1:4)] <- 0
将替换A[1,1]
、 A[2,2]
、 A[3,3]
和A[4,4]
为 0 . 事实上,如果A
有“dimnames”属性(你指的“rownames”和“colnames”),我们也可以使用字符串作为索引。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.