I’d like to convert a function into a string – further I’d like to use purrr::map()
to turn many functions into strings. The motivating problem is to apply many functions to a data frame, and return a new data frame where the column names depend on the function that was applied.
My function_to_string()
function works fine on its own, but when I try to use it inside purrr::map()
, I obtain the error Can't convert to a symbol.
.
function_to_string <- function(fun) {
rlang::as_string(rlang::ensym(fun))
}
function_to_string(mean)
#> [1] "mean"
function_to_string(sd)
#> [1] "sd"
# I can't map over functions with function_to_string()
purrr::map(c(mean, sd), function_to_string)
#> Error in `purrr::map()`:
#> ℹ In index: 1.
#> Caused by error in `rlang::ensym()`:
#> ! Can't convert to a symbol.
# but mapping over functions is possible
purrr::map(c(mean, sd), (fn) fn(1:10))
#> [[1]]
#> [1] 5.5
#>
#> [[2]]
#> [1] 3.02765
Created on 2024-06-03 with reprex v2.1.0