user3507085
user3507085

Reputation: 720

Convert R function to string

I would like to convert a function object into a string

fn=function(x)
{
  return(2*x)
}

my_convert_function(fn)

# would give 
#"fn=function(x)
#{
#  return(2*x)
#}"

Is it possible to do it ? Thank you for your ideas

Upvotes: 4

Views: 277

Answers (2)

David J. Bosak
David J. Bosak

Reputation: 1624

As of R 4.0, there is also deparse1(). This version of deparse() returns a single string directly (if that is what you are looking for):

fn=function(x)
{
  return(2*x)
}
  
deparse1(fn)

#> [1] "function (x)  {     return(2 * x) }"

Upvotes: 0

Alexey Ferapontov
Alexey Ferapontov

Reputation: 5169

deparse(fn)
[1] "function (x) "     "{"                 "    return(2 * x)" "}"

Upvotes: 5

Related Questions