I have a set of functions funs <- c(mean, median, min, max, quantile)
which I want to apply to a numeric vector values
. This can easily done with sapply()
but with its result none of the elements has a name. I want each list element named based on the applied function. I tried:
funs <- c(mean, median, min, max, quantile)
some_vals <- c(rnorm(14))
stats <- sapply(funs, function(fun) {
result <- fun(some_vals)
names(result) <- deparse(substitute(fun))
return(result)
}
)
But with that every list element is named X[[i]]. How can I name the list elements according to the applied function(s)?
The difficulty is that once you store the functions objects inside a list, they no longer have a name unless you specify a name for that object in the list.
I would use strings for the function names then match.fun
inside sapply
. This is easy to do and you get the names for free.
funs <- c("mean", "median", "min", "max", "quantile")
some_vals <- c(rnorm(14))
sapply(funs, function(fun) match.fun(fun)(some_vals))
#> $mean
#> [1] -0.06134755
#>
#> $median
#> [1] -0.3473996
#>
#> $min
#> [1] -2.140686
#>
#> $max
#> [1] 1.940046
#>
#> $quantile
#> 0% 25% 50% 75% 100%
#> -2.1406864 -0.7488198 -0.3473996 0.7707063 1.9400459
The alternative is to name your list:
funs <- c(mean = mean, median = median, min = min, max = max,
quantile = quantile)
sapply(funs, function(fun) fun(some_vals))
#> $mean
#> [1] -0.06134755
#>
#> $median
#> [1] -0.3473996
#>
#> $min
#> [1] -2.140686
#>
#> $max
#> [1] 1.940046
#>
#> $quantile
#> 0% 25% 50% 75% 100%
#> -2.1406864 -0.7488198 -0.3473996 0.7707063 1.9400459
Created on 2023-08-21 with reprex v2.0.2