'Is there a way to simplify this dplyr (summarise) code - summarize multiple variables in one statement

I have the following working code (I have not included the data as I don't think it is necessary to anyone able to answer this question)...

I have a feeling this should be possible within one pipe/ one statement. Does anyone know a cleaner way?

df1 <- df %>%
  group_by(x,y,z) %>%
  summarize(mean = mean(a))

df2 <- df %>%
  group_by(x,y,z) %>%
  summarize(count = n())

df_merged <- merge(df1,df2, all=TRUE)


Solution 1:[1]

Just do multiple variables like count, mean or sd in summarize. You can use this:

df %>%
  group_by(x,y,z) %>%
  summarize(count = n(),
            mean = mean(a))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quinten