Adding 5th and 95th Percentile to List in R

Is there a method to add in 5th and 95th percentile to the list below?

mtcars %>% summarize(across(where(is.numeric), list(median = median), na.rm = TRUE))

I tried the below, but I think I am missing something.

mtcars %>% summarize(across(where(is.numeric), list(mean = mean, q95=quantile(, .95), q5=quantile(, .05)), na.rm = TRUE))

Any help would be appreciated! Thanks!

>Solution :

You may want to use ~ with across in your list like this:

library(dplyr)
mtcars %>%
  summarise(across(where(is.numeric), list(mean = ~mean(.), 
                                           q5 = ~quantile(., 0.05), 
                                           q95 = ~quantile(., 0.95))))
#>   mpg_mean mpg_q5 mpg_q95 cyl_mean cyl_q5 cyl_q95 disp_mean disp_q5 disp_q95
#> 1 20.09062 11.995    31.3   6.1875      4       8  230.7219   77.35      449
#>    hp_mean hp_q5 hp_q95 drat_mean drat_q5 drat_q95 wt_mean wt_q5  wt_q95
#> 1 146.6875 63.65 253.55  3.596563  2.8535   4.3145 3.21725 1.736 5.29275
#>   qsec_mean qsec_q5 qsec_q95 vs_mean vs_q5 vs_q95 am_mean am_q5 am_q95
#> 1  17.84875 15.0455  20.1045  0.4375     0      1 0.40625     0      1
#>   gear_mean gear_q5 gear_q95 carb_mean carb_q5 carb_q95
#> 1    3.6875       3        5    2.8125       1      4.9

Created on 2023-02-24 with reprex v2.0.2

Leave a Reply