Hello,
I think it would be better if you could provide a full reprex of your problem. This includes some actual sample data (like across what type of columns are you looping?). Also, your provided code cannot work (see e.g. your definition of quantile
, which is missing a c()
call. The actual loop you created is also missing, so maybe it is not a problem with the function but the loop you did.
If you could reformulate your question and provide some data (e.g. with dput(head(data, 15))
and include the actual loop, I think you would have a greater chance to get actual answers that are valuable to you.
Regarding your function, I just did a minor tweek regarding the grouping variable since it adds more flexibility. And you could use purrr::map()
instead of Map()
, since it is better practice imo.
library('tidyverse')
# added grouping var for flexibility
percentiles <- function(data, group_var, pick_var){
# added c() call
quantile <- c(.25, .5, .75)
# indentation
data |>
group_by(!!sym(group_var)) |>
summarise(
quant25 = quantile(!!sym(pick_var), probs = quantile[1]),
quant50 = quantile(!!sym(pick_var), probs = quantile[2]),
quant75 = quantile(!!sym(pick_var), probs = quantile[3])
)
# return is not necessary if the last item you evaluate is the output
# return(quantiles)
}
pick_var_list <- c('disp','wt','qsec')
output_one <- purrr::map(.x = pick_var_list,
.f = percentiles,
data = mtcars,
group_var = 'cyl')
output_one
#> [[1]]
#> # A tibble: 3 × 4
#> cyl quant25 quant50 quant75
#> <dbl> <dbl> <dbl> <dbl>
#> 1 4 78.8 108 121.
#> 2 6 160 168. 196.
#> 3 8 302. 350. 390
#>
#> [[2]]
#> # A tibble: 3 × 4
#> cyl quant25 quant50 quant75
#> <dbl> <dbl> <dbl> <dbl>
#> 1 4 1.88 2.2 2.62
#> 2 6 2.82 3.22 3.44
#> 3 8 3.53 3.76 4.01
#>
#> [[3]]
#> # A tibble: 3 × 4
#> cyl quant25 quant50 quant75
#> <dbl> <dbl> <dbl> <dbl>
#> 1 4 18.6 18.9 20.0
#> 2 6 16.7 18.3 19.2
#> 3 8 16.1 17.2 17.6
Created on 2022-09-26 with reprex v2.0.2
Kind regards