Bangyou
Bangyou

Reputation: 9816

Convert function into string

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.

Upvotes: 14

Views: 5316

Answers (2)

David J. Bosak
David J. Bosak

Reputation: 1624

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

Upvotes: 11

Rich Scriven
Rich Scriven

Reputation: 99331

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] "}"  

Upvotes: 19

Related Questions