R:逐元素矩阵除法 [英] R: element-wise matrix division
问题描述
给出相同维的两个数值矩阵A
和B
.按元素划分的最佳方法是什么:A[i,j] / B[i,j]
?我知道可以使用双for
循环.但是我想要最有效的方法.
Given two numeric matrices A
and B
of the same dimension. What's the best way for element-wise division: A[i,j] / B[i,j]
? I know it is possible to do using double for
loops. But I want the most efficient way.
编辑:当存在B[i,j] == 0
时,必须为A[i,j] <- 0
.
When there is a B[i,j] == 0
it will have to be A[i,j] <- 0
.
推荐答案
如果矩阵是A
和B
,则只需使用A / B
.
If your matrices are A
and B
, you can just use A / B
.
A <- matrix(1:4, 2, 2)
# [,1] [,2]
#[1,] 1 3
#[2,] 2 4
B <- matrix((1:4) * 2, 2, 2)
# [,1] [,2]
#[1,] 2 6
#[2,] 4 8
C <- A / B
# [,1] [,2]
#[1,] 0.5 0.5
#[2,] 0.5 0.5
如果有
B[i,j] == 0
,则必须为A[i,j] <- 0
.
如果B
中有0个元素,则可能会得到NaN
,Inf
或-Inf
,具体取决于A
中的对应内容.
In case you have 0 elements in B
, you may get NaN
, Inf
or -Inf
, depending on its counterpart in A
.
0 / 0
# NA
1 / 0
# Inf
-1 / 0
# -Inf
所有这些都不是有限的.如果要将它们替换为0,只需执行以下操作:
All these are not finite. If you want to replace them with 0, simply do:
C <- A / B
C[!is.finite(C)] <- 0
很难记住R如何对待NA
,NaN
,Inf
和-Inf
.您可以阅读?is.finite
和?NA
以获得常规信息.在这里,我将做一个简单的测试.
It is difficult to remember how R treats NA
, NaN
, Inf
and -Inf
. You can read ?is.finite
and ?NA
for general info. Here I will give a simple test.
x <- c(NA, NaN, Inf, -Inf)
is.finite(x)
# [1] FALSE FALSE FALSE FALSE
is.infinite(x)
# [1] FALSE FALSE TRUE TRUE
is.na(x)
# [1] TRUE TRUE FALSE FALSE
is.nan(x)
# [1] FALSE TRUE FALSE FALSE
请注意,is.infinite
不是is.finite
的倒数,而是is.na
的倒数.这就是为什么我使用!is.finite
.
Note, is.infinite
is not the inverse of is.finite
, but the inverse of is.na
. That is why I have used !is.finite
.
这篇关于R:逐元素矩阵除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!