Skip to contents

Summarise data frame variables according to group

Usage

summarise_by_group(df, grp.cols, summarise.cols, fun)

Arguments

df

A data frame

grp.cols

Index the columns to group by. Can index by column name or column number.

summarise.cols

Index the columns that should be summarised. Can index by column name or column number.

fun

The function for summarising (e.g., mean, max etc.)

Value

A data frame

Examples

summarise_by_group(mtcars, "cyl", c(1, 3:ncol(mtcars)), max)
#>   cyl  mpg  disp  hp drat    wt  qsec vs am gear carb
#> 1   4 33.9 146.7 113 4.93 3.190 22.90  1  1    5    2
#> 2   6 21.4 258.0 175 3.92 3.460 20.22  1  1    5    6
#> 3   8 19.2 472.0 335 4.22 5.424 18.00  0  1    5    8
summarise_by_group(mtcars, 2, c(1, 3:ncol(mtcars)), max)
#>   cyl  mpg  disp  hp drat    wt  qsec vs am gear carb
#> 1   4 33.9 146.7 113 4.93 3.190 22.90  1  1    5    2
#> 2   6 21.4 258.0 175 3.92 3.460 20.22  1  1    5    6
#> 3   8 19.2 472.0 335 4.22 5.424 18.00  0  1    5    8
summarise_by_group(mtcars, c(2, 10), c(1, 3, 5:9), max)
#>   cyl gear  mpg  disp drat    wt  qsec vs am
#> 1   4    3 21.5 120.1 3.70 2.465 20.01  1  0
#> 2   4    4 33.9 146.7 4.93 3.190 22.90  1  1
#> 3   4    5 30.4 120.3 4.43 2.140 16.90  1  1
#> 4   6    3 21.4 258.0 3.08 3.460 20.22  1  0
#> 5   6    4 21.0 167.6 3.92 3.440 18.90  1  1
#> 6   6    5 19.7 145.0 3.62 2.770 15.50  0  1
#> 7   8    3 19.2 472.0 3.73 5.424 18.00  0  0
#> 8   8    5 15.8 351.0 4.22 3.570 14.60  0  1
summarise_by_group(mtcars, "cyl", c("mpg", "disp"), max)
#>   cyl  mpg  disp
#> 1   4 33.9 146.7
#> 2   6 21.4 258.0
#> 3   8 19.2 472.0
summarise_by_group(mtcars, "cyl", "mpg", max)
#>   cyl  mpg
#> 1   4 33.9
#> 2   6 21.4
#> 3   8 19.2
summarise_by_group(mtcars, c("cyl",'gear'), c("mpg", "disp"), max)
#>   cyl gear  mpg  disp
#> 1   4    3 21.5 120.1
#> 2   4    4 33.9 146.7
#> 3   4    5 30.4 120.3
#> 4   6    3 21.4 258.0
#> 5   6    4 21.0 167.6
#> 6   6    5 19.7 145.0
#> 7   8    3 19.2 472.0
#> 8   8    5 15.8 351.0
summarise_by_group(mtcars, "cyl", c(1,3), max)
#>   cyl  mpg  disp
#> 1   4 33.9 146.7
#> 2   6 21.4 258.0
#> 3   8 19.2 472.0