【问题标题】:Dplyr produces NaN while base R produces NADplyr 产生 NaN 而 base R 产生 NA
【发布时间】:2018-05-28 14:00:17
【问题描述】:

考虑以下玩具数据和计算:

library(dplyr)

df <-  tibble(x = 1)

stats::sd(df$x)

dplyr::summarise(df, sd_x = sd(x))

第一个计算结果为NA,而第二个计算结果包含在 dplyr 函数summarise 中时产生NaN。我希望这两种计算都会产生相同的结果,但我想知道它们为什么不同?

【问题讨论】:

  • 我可以复制。 dplyr 版本 0.7.4 - CRAN 的最新版本。
  • 这里也一样。但是,您需要它做什么?如果您询问is.na(),两者都返回TRUE
  • 有趣。对我来说,结果都是 NA:&gt; stats::sd(df$x) [1] NA&gt; dplyr::summarise(df, sd_x = sd(x)) # A tibble: 1 x 1 sd_x &lt;dbl&gt; 1 NA
  • @storaged 你使用的是什么版本的dplyr

标签: r dplyr nan na


【解决方案1】:

它正在调用不同的函数。我不清楚这个函数是什么,但不是stats那个。

dplyr::summarise(df, sd_x = stats::sd(x))
# A tibble: 1 x 1
   sd_x
  <dbl>
1    NA

debugonce(sd) # debug to see when sd is called

这里没有调用:

dplyr::summarise(df, sd_x = sd(x))
# A tibble: 1 x 1
   sd_x
  <dbl>
1   NaN

但在这里调用:

dplyr::summarise(df, sd_x = stats::sd(x))
debugging in: stats::sd(1)
debug: sqrt(var(if (is.vector(x) || is.factor(x)) x else as.double(x), 
    na.rm = na.rm))
...

更新

看来summarise 中的sd 是在R 之外计算的,在此头文件中有所暗示:https://github.com/tidyverse/dplyr/blob/master/inst/include/dplyr/Result/Sd.h

dplyr 似乎重新定义了许多函数。鉴于var 在两种情况下都给出了相同的结果,我认为 sd 行为是一个错误。

【讨论】:

  • 你的 R dplyr 和 R 版本是什么?我很惊讶我无法重现该错误...
  • 当我做dplyr::mutate(df, var_x = var(x)) 时,我也会得到NA。根据行为是错误的建议,我已接受此答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
  • 2015-12-02
  • 1970-01-01
  • 2017-11-26
  • 1970-01-01
  • 2018-01-07
  • 2010-12-23
相关资源
最近更新 更多