How to combine two different dplyr summaries in a single command

Viewed 1923

I am trying to create a grouped summary that reports the number of records in each group and then also shows the means of a series of variables.

I can only work out how to do this as two separate summaries which I then join together. This works fine but I wonder if there is a more elegant way to do this?

dailyn<-daily %>% # this summarises n
  group_by(type) %>%
  summarise(n=n()) %>%

dailymeans <- daily %>% # this summarises the means
  group_by(type) %>%
  summarise_at(vars(starts_with("d.")),funs(mean(., na.rm = TRUE))) %>%

dailysummary<-inner_join(dailyn,dailymeans) #this joins the two parts together

The data I'm working with is a dataframe like this:

daily<-data.frame(type=c("A","A","B","C","C","C"),
                  d.happy=c(1,5,3,7,2,4),
                  d.sad=c(5,3,6,3,1,2))
2 Answers
Related