简体   繁体   中英

Turning a string into a function line in R

I am relatively new to R and I would like to do the following: if I write a simple function as

fn<-function(K) K^2

and then compute fn(10) , I get 100.

Now if K^2 is created somewhere as a string, t1="K^2" , then obviously my function does not work anymore since it does not take K as a variable.

How can I turn a string, a sequence of characters into a line in my function?

I don't want to use eval(parse(text=t1)) , because I would like to use my function later in another function, say to find the gradient using n1.grad(x0,fn) .

Thanks, Yasin

You don't need to use eval ( parse()) but you do need to use parse , since translating text to syntactically acceptable (but unevaluated) parse trees is what parsing does. There are three components of a function that can be modified: arglist, body, and environment, and they each have an assignment function. Here we are only modifying the body with body<- :

?`function`
?`body<-`

fn <- function(K) {}
t1="K^2"
body(fn) <- parse(text=t1)
fn
#----------
function (K) 
K^2

And there is always:

fortunes::fortune(106)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM