summarise_all multiple functions with arguments

Example from dplyr page shows how to supply argument to a function in summarise_all:

library(dplyr)

iris %>% 
  group_by(Species) %>% 
  summarise_all(list(Q3 = quantile), probs = 0.75)
#> # A tibble: 3 x 5
#>   Species    Sepal.Length_Q3 Sepal.Width_Q3 Petal.Length_Q3 Petal.Width_Q3
#>   <fct>                <dbl>          <dbl>           <dbl>          <dbl>
#> 1 setosa                 5.2           3.68            1.58            0.3
#> 2 versicolor             6.3           3               4.6             1.5
#> 3 virginica              6.9           3.18            5.88            2.3

Created on 2019-07-08 by the reprex package (v0.3.0)

The page also gives example such as summarise_all(list(min = min, max = max)) for two functions and What I got stuck is how to supply arguments when we have more than one functions. For example, how can I add Q1 with argument 0.25 for function quantile as well so I got both Sepal.Length_Q3 and Sepal.Length_Q1?

One possibility:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

iris %>%
  group_by(Species) %>%
  summarise_all(.funs = list(Q1 = ~ quantile(x = ., probs = 0.25),
                             Q3 = ~ quantile(x = ., probs = 0.75)))
#> # A tibble: 3 x 9
#>   Species Sepal.Length_Q1 Sepal.Width_Q1 Petal.Length_Q1 Petal.Width_Q1
#>   <fct>             <dbl>          <dbl>           <dbl>          <dbl>
#> 1 setosa             4.8            3.2              1.4            0.2
#> 2 versic~            5.6            2.52             4              1.2
#> 3 virgin~            6.22           2.8              5.1            1.8
#> # ... with 4 more variables: Sepal.Length_Q3 <dbl>, Sepal.Width_Q3 <dbl>,
#> #   Petal.Length_Q3 <dbl>, Petal.Width_Q3 <dbl>

Created on 2019-07-09 by the reprex package (v0.3.0)

5 Likes

Thanks for the quick reply. Very straightforward.

I have not used the ~ format. Something to learn ... :thinking:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.