Convert function into string
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] "}"
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