1

I am aggregating some data and I want to add group sizes N to the output table. Until recently, the code below worked fine. Now, N is equal to the rowcount of my table.

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 
tomaz
  • 493
  • 4
  • 13
  • 1
    The code above does work for me and gives the correct results (N=50 for each group). Did you restart R? Which other packages are you loading? – deschen Jan 26 '21 at 08:39
  • I get `N` column as 50 for each `Species`. What is your `packageVersion('dplyr')` ? – Ronak Shah Jan 26 '21 at 08:39
  • Restarting R doesn't help. I'm only loading the `tidyverse` package version 1.3.0. The `packageVersion('dplyr')` is 1.0.3. – tomaz Jan 26 '21 at 08:41

2 Answers2

3

This looks like a recently introduced bug. Can be reproduced on dplyr 1.0.3 but not on 1.0.2.

You could however, avoid the second group_by completely in this case.

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Try this:

rm(list = ls())
library(dplyr)
iris %>% 
  group_by(Species) %>% 
  group_by(N = n(), .add = TRUE) %>% 
  summarise_all(list(~mean(., na.rm = TRUE))) 

TarJae
  • 72,363
  • 6
  • 19
  • 66