R:逐元素矩阵除法 [英] R: element-wise matrix division

查看:112
本文介绍了R:逐元素矩阵除法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出相同维的两个数值矩阵AB.按元素划分的最佳方法是什么: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.

推荐答案

如果矩阵是AB,则只需使用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个元素,则可能会得到NaNInf-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如何对待NANaNInf-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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆