首页 > 解决方案 > 不确定为什么 dplyr 中的 group_by 函数不起作用

问题描述

我是 R 新手,并试图了解 dplyr 的工作原理,以便我可以将其应用于我拥有的数据集。我正在尝试使用 starwars API 完成此示例: https ://cran.r-project.org/web/packages/dplyr/vignettes/dplyr.html

我正在尝试按物种和性别对星球大战数据框进行分组,然后找到每个物种和性别的平均值。代码是从教程中复制的:

starwars %>%
  group_by(species, sex) %>%
  select(height, mass) %>%
  summarise(
    height = mean(height, na.rm = TRUE),
    mass = mean(mass, na.rm = TRUE)
  )

我应该得到这个输出:

#> Adding missing grouping variables: `species`, `sex`
#> `summarise()` has grouped output by 'species'. You can override using the `.groups` argument.
#> # A tibble: 41 x 4
#> # Groups:   species [38]
#>   species  sex   height  mass
#>   <chr>    <chr>  <dbl> <dbl>
#> 1 Aleena   male      79    15
#> 2 Besalisk male     198   102
#> 3 Cerean   male     198    82
#> 4 Chagrian male     196   NaN
#> # … with 37 more rows

但相反,我得到了这个:

#> Adding missing grouping variables: `species`, `sex`
#>    height     mass
#> 1 174.358 97.31186

有人可以帮我理解为什么它会将所有物种和性别合并在一起,然后取身高和质量的平均值,而不是保持单独的群体吗?

谢谢!

标签: rdplyrgroup-by

解决方案


推荐阅读