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.
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
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] "}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With