2

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

data paRty
  • 218
  • 1
  • 7
yasin
  • 23
  • 2
  • 1
    There is probably an alternative for this. This seems like bad practice and almost impossible to debug. It may also cause problems when you deal with multiple parameters/arguments – masfenix Apr 02 '15 at 21:03

1 Answers1

5

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)
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • 1
    just the usual reminder that if `t1` is from an untrusted source, you probably shouldn't be evaluating it as it could easily contain `unlink("/", TRUE, TRUE)` or some such. – BrodieG Apr 02 '15 at 21:17
  • Ouch. Or some `system()` call. – IRTFM Apr 02 '15 at 21:20
  • would you add an example for arglist and environment for my learning purpose. Thanks – Sathish Apr 02 '15 at 21:21
  • I'm pretty sure I have already posted examples on SO for using `environment<-` (needed when hacking functions that call non-exported functions) Here's an example: http://stackoverflow.com/questions/27671317/stargazer-model-names-instead-of-numbers/27672401#27672401 . For the arglist part, just following the links on the `?'function'` help page appears perfectly adequate. You should post a question if something is unclear after you have made a good faith effort to answer your own questions. – IRTFM Apr 02 '15 at 21:40
  • BondedDust, thanks so much for taking the time to answer my question! BrodieG, thanks for the reminder. – yasin Apr 03 '15 at 22:16