使用 summarise() 函数时标准偏差出现 NA

Standard Deviation coming up NA when using summarise() function

我正在尝试为在 RStudio 中找到的出生体重数据集 (birthwt) 计算描述性统计数据。但是,我只对几个变量感兴趣:ageftvptllwt

这是我目前的代码:

library(MASS)
library(dplyr)
data("birthwt")

grouped <- group_by(birthwt, age, ftv, ptl, lwt)

summarise(grouped, 
          mean = mean(bwt),
          median = median(bwt),
          SD = sd(bwt))

它给了我一个漂亮的打印 table 但只有有限数量的 SD 被填充,其余的说 NA。我只是不知道为什么或如何解决它!

部分组的行数为 1。

grouped %>% 
     summarise(n = n())
# A tibble: 179 x 5
# Groups: age, ftv, ptl [?]
#     age   ftv   ptl   lwt     n
#   <int> <int> <int> <int> <int>
# 1    14     0     0   135     1
# 2    14     0     1   101     1
# 3    14     2     0   100     1
# 4    15     0     0    98     1
# 5    15     0     0   110     1
# 6    15     0     0   115     1
# 7    16     0     0   110     1
# 8    16     0     0   112     1
# 9    16     0     0   135     2
#10    16     1     0    95     1

根据?sd

The standard deviation of a length-one vector is NA.

这导致 sd 的值 NA 只有一个元素

我在这里偶然发现了另一个原因,对我来说,答案来自 docs:

# BEWARE: reusing variables may lead to unexpected results
mtcars %>%
    group_by(cyl) %>%
    summarise(disp = mean(disp), sd = sd(disp))
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 3 x 3
#>     cyl  disp    sd
#>   <dbl> <dbl> <dbl>
#> 1     4  105.    NA
#> 2     6  183.    NA
#> 3     8  353.    NA

所以,如果有人和我有同样的原因,与其重复使用变量,不如创建新变量:

mtcars %>%
group_by(cyl) %>%
summarise(
    disp_mean = mean(disp),
    disp_sd = sd(disp)
)

`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 3 x 3
    cyl disp_mean disp_sd
  <dbl>     <dbl>   <dbl>
1     4      105.    26.9
2     6      183.    41.6
3     8      353.    67.8