R:为什么意思是(NA,na.rm = TRUE)返回NaN [英] R: Why does mean(NA, na.rm = TRUE) return NaN
问题描述
当使用所有NA的向量估计均值时,如果na.rm = TRUE
,则得到NaN
.为什么会这样,这是有缺陷的逻辑,还是我想念的东西?当然,使用NA
比使用NaN
更有意义?
When estimating the mean with a vector of all NA's we get an NaN
if na.rm = TRUE
. Why is this, is this flawed logic or is there something I'm missing? Surely it would make more sense to use NA
than NaN
?
下面的简单示例
mean(NA, na.rm = TRUE)
#[1] NaN
mean(rep(NA, 10), na.rm = TRUE)
#[1] NaN
推荐答案
?mean
没有对此说任何话,这有点可惜. 我的评论仅告诉您申请mean
在空的数字"上使用NaN
会导致没有更多理由. Rui Barradas的评论试图解释这一点,但并非如此精确,因为除以0
并不总是NaN
,它可以是Inf
或-Inf
.我曾经在 R:基于元素的矩阵除法中对此进行过讨论.但是,我们正在接近.尽管mean(x)
没有用sum(x) / length(x)
编码,但是这个数学事实确实解释了NaN
.
It is a bit pity that ?mean
does not say anything about this. My comment only told you that applying mean
on an empty "numeric" results in NaN
without more reasoning. Rui Barradas's comment tried to reason this but was not accurate, as division by 0
is not always NaN
, it can be Inf
or -Inf
. I once discussed about this in R: element-wise matrix division. However, we are getting close. Although mean(x)
is not coded by sum(x) / length(x)
, this mathematical fact really explains this NaN
.
来自?sum:
*NB:* the sum of an empty set is zero, by definition.
所以sum(numeric(0))
是0
.因为length(numeric(0))
是0
,所以mean(numeric(0))
是0 / 0
,它是NaN
.
So sum(numeric(0))
is 0
. As length(numeric(0))
is 0
, mean(numeric(0))
is 0 / 0
which is NaN
.
这篇关于R:为什么意思是(NA,na.rm = TRUE)返回NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!