0

Say I have the following dataframe:

df <- data.frame(Day=c(1,1,2,2), Temp=c(30,20,10,50), Humidity=c(0.5,0.2,0.1,0.5))

i.e.

  Day Temp Humidity
1   1   30      0.5
2   1   20      0.2
3   2   10      0.1
4   2   50      0.5

Using only the base packages, I would compute the average for each day by doing:

aggregate(. ~ Day, df, mean)

And get:

  Day Temp Humidity
1   1   25     0.35
2   2   30     0.30

But I want to use tidyverse. I know, I can do the same doing:

df %>% group_by(Day) %>% summarise(Temp=mean(Temp), Humidity=mean(Humidity))

But is there a way to say, I want the average of every column. I want to use this in situations where I have dozens of columns.

1 Answers1

5

summarise_all does this:

df %>%
    group_by(Day) %>%
    summarise_all(mean)
Marius
  • 58,213
  • 16
  • 107
  • 105