yasin
yasin

Reputation: 23

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

Upvotes: 2

Views: 84

Answers (1)

IRTFM
IRTFM

Reputation: 263499

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)

Upvotes: 5

Related Questions