Group by and find means of all numeric varables

Viewed 96

I have a data set with about a hundred variables, so the easiest way for me to get the means by group is as follows:

iris %>%
group_by(species) %>%
summarise_if(is.numeric, mean, na.rm=T)

However, I also want to know the N within each mean count as well. R does not accept n() inside summarise_if.

I could manually type out each variable like this, but I have hundred of variables so that won't work.

iris %>% group_by(Species) %>% 
summarise(mean_sl = mean(Sepal.Length), mean_sw = mean(Sepal.Width), 
mean_pl = mean(Petal.Length), mean_pw = mean(Petal.Width), n())

Any idea's how I can get the mean, as well as the N for each numeric variable in my dataset?

1 Answers

With dplyr 1.0.0, we can use across with summarise where multiple functions can be applied as in a regular summarise as well groups or blocks of columns in across

library(dplyr)
iris %>% 
   group_by(Species) %>%
   summarise(across(where(is.numeric), mean, na.rm = TRUE), n = n())

Based on the OP's comments, if we need to find the number of missing values per each column along with mean of each column, we can have different sets of across (if different sets of columns are used)

iris %>%
   summarise(across(where(is.numeric), mean, na.rm = TRUE),
             across(where(is.numeric), ~ sum(is.na(.)), .names = '{col}_n'))

or have a single across with different functions

iris %>%
    summarise(across(where(is.numeric), 
          list(mean = ~ mean(., na.rm = TRUE), n = ~ sum(is.na(.)))))
Related