Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dplyr summarize with different operations for multiple columns

Tags:

r

dplyr

Well, I know that there are already tons of related questions, but none gave an answer to my particular need.

I want to use dplyr "summarize" on a table with 50 columns, and I need to apply different summary functions to these.

"Summarize_all" and "summarize_at" both seem to have the disadvantage that it's not possible to apply different functions to different subgroups of variables.

As an example, let's assume the iris dataset would have 50 columns, so we do not want to address columns by names. I want the sum over the first two columns, the mean over the third and the first value for all remaining columns (after a group_by(Species)). How could I do this?

like image 642
CodingButStillAlive Avatar asked Feb 23 '18 09:02

CodingButStillAlive


People also ask

Can you Summarise by multiple columns in R?

Apply Multiple Summarise Functions Similarly, you can also perform multiple aggregation functions on all summarise columns in R. This example does the group by on department and state columns, summarises on salary and bonus columns, and apply the sum & mean functions on each summarised column.

What does %>% do in dplyr?

%>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression. It is defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).


1 Answers

Fortunately, there is a much simpler way available now. With the new dplyr 1.0.0 coming out soon, you can leverage the across function for this purpose.

All you need to type is:

iris %>% 
  group_by(Species) %>% 
  summarize(
    # I want the sum over the first two columns, 
    across(c(1,2), sum),
    #  the mean over the third 
    across(3, mean),
    # the first value for all remaining columns (after a group_by(Species))
    across(-c(1:3), first)
  )

Great, isn't it? I first thought the across is not necessary as the scoped variants worked just fine, but this use case is exactly why the across function can be very beneficial.

You can get the latest version of dplyr by devtools::install_github("tidyverse/dplyr")

like image 50
Agile Bean Avatar answered Nov 03 '22 00:11

Agile Bean