Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert function into string

Tags:

r

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.

like image 490
Bangyou Avatar asked Oct 22 '15 21:10

Bangyou


2 Answers

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
like image 66
David J. Bosak Avatar answered Sep 30 '22 18:09

David J. Bosak


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] "}"  
like image 24
Rich Scriven Avatar answered Sep 30 '22 19:09

Rich Scriven