I have defined a variable which is a list of function.
var_function <- mean
I could use any functions. How could I convert function mean
into a string? Thanks for any suggestion. Please let me know if my question is not clear.
Join Stack Overflow to learn, share knowledge, and build your career.
I have defined a variable which is a list of function.
var_function <- mean
I could use any functions. How could I convert function mean
into a string? Thanks for any suggestion. Please let me know if my question is not clear.
You can turn any function into a line-by-line character vector with deparse()
.
deparse(setNames)
# [1] "function (object = nm, nm) "
# [2] "{"
# [3] " names(object) <- nm"
# [4] " object"
# [5] "}"
paste0(deparse(fun), collapse = " ")
– Brandon Bertelsen
Jul 15 '17 at 3:28
deparse()
works well for this particular question, in which var_function
is fed as a variable. If it is fed as a string, however, ("var_function"
), then deparse(get())
can be used: deparse(get("var_function"))
.
– Christian
Dec 27 '20 at 10:55
As of R 4.0, there is also deparse1()
. This will return the function as a single string.
f <- function(x) {
x + 2
}
strf <- deparse1(f)
strf
#> [1] "function (x) { x + 2 }"
To get the function string back to a real function, use eval()
with str2lang()
:
f2 <- eval(str2lang(strf))
f2(4)
#> 6
mean
as a character or do you want the name of the function (i.e."mean"
) as a character? – joran Oct 22 '15 at 21:46