Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

r - Coerce a function into an expression?

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='
'))

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

Is there a better way already implemented in R?

question from:https://stackoverflow.com/questions/65871403/coerce-a-function-into-an-expression

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...