Coerce a function into an expression?

Viewed 26

Is there any function or method that coerces a function object into an expression in R?

Suppose I have u = function (x, y) 2 * x^0.8 * y^0.2. What I would like to achieve is convert u into a call or expression object. Example, 2 * x^0.8 * y^0.2 with mode(.) == 'call' or expression(2 * x^0.8 * y^0.2)

I know that you can do something like:


str2lang(deparse(u)[[2]])
2 * x^0.8 * y^0.2

deparse can still be made to work for cases when functions have several lines.

ff = function(x, y) {
        x = x + 1
        y = y + 1
        return(x+y) 
        }

str2lang(paste(deparse(ff)[-1], collapse='\n'))

{
    x = x + 1
    y = y + 1
    return(x + y)
}

Is there a better way already implemented in R?

1 Answers

Use body. No packages are used.

b <- body(ff)

# test
eval(b, list(x = 3, y = 10))
## [1] 15

# compare to ff
ff(x = 3, y = 10)
## [1] 15
Related