Dplyr 产生 NaN 而 base R 产生 NA

Dplyr produces NaN while base R produces NA

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

library(dplyr)

df <-  tibble(x = 1)

stats::sd(df$x)

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

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

它正在调用一个不同的函数。我不清楚这个功能是什么,但它不是 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 行为是一个错误。