我正在聚合一些数据,并希望将组大小N添加到输出表中。直到最近,下面的代码都运行得很好。现在,N等于我的表的行数。
iris %>%
group_by(Species) %>%
group_by(N = n(), .add = TRUE) %>%
summarise_all(list(~mean(., na.rm = TRUE)))
# A tibble: 3 x 6
# Groups: Species [3]
Species N Sepal.Length Sepal.Width Petal.Length Petal.Width
<fct> <int> <dbl> <dbl> <dbl> <dbl>
1 setosa 150 5.01 3.43 1.46 0.246
2 versicolor 150 5.94 2.77 4.26 1.33
3 virginica 150 6.59 2.97 5.55 2.03 发布于 2021-01-26 16:50:08
这看起来像是最近引入的一个bug。可以在dplyr 1.0.3上重现,但不能在1.0.2上重现。
但是,在这种情况下,您可以完全避免第二个group_by。
library(dplyr)
iris %>%
group_by(Species) %>%
summarise(across(.fns = mean, na.rm = TRUE),
N = n())
# Species Sepal.Length Sepal.Width Petal.Length Petal.Width N
#* <fct> <dbl> <dbl> <dbl> <dbl> <int>
#1 setosa 5.01 3.43 1.46 0.246 50
#2 versicolor 5.94 2.77 4.26 1.33 50
#3 virginica 6.59 2.97 5.55 2.03 50发布于 2021-01-26 16:51:07
试试这个:
rm(list = ls())
library(dplyr)
iris %>%
group_by(Species) %>%
group_by(N = n(), .add = TRUE) %>%
summarise_all(list(~mean(., na.rm = TRUE))) https://stackoverflow.com/questions/65898076
复制相似问题