Turning a string into a functional string in R

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

fn<-function(K) K^2

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

Now, if K^2created somewhere as a string, t1="K^2"then, obviously, my function no longer works, since it does not accept K as a variable.

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

I do not 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).

Thank you, Yasin

+2
source share
1 answer

eval ( parse()), parse, ( ) - , . , : arglist, body environment, . body<-:

?`function`
?`body<-`

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

:

fortunes::fortune(106)
+5

All Articles