Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a function's code to a string?

Tags:

r

Suppose I have:

test <- function(x) x + 1
test
function(x)
  x + 1

I would like to somehow save the output produced by invoking test to a string (i.e. the function declaration) but can't think of a way to do it.

like image 211
Denis Avatar asked Dec 07 '22 11:12

Denis


1 Answers

We can use deparse

paste(deparse(test), collapse = " ")
#[1] "function (x)  x + 1"

Also, if we need to extract the components of the function, use body

body(test)

Or split it to a list

as.list(test)
like image 164
akrun Avatar answered Dec 23 '22 13:12

akrun