Is there another way to transform a string of characters into a function other than the following?
Example: x+2
f <- function(x) {
eval( parse(text=("x+2")) )
}
print( f(2) )
4
I do not find an alternative way.
Thanks you
Is there another way to transform a string of characters into a function other than the following?
Example: x+2
f <- function(x) {
eval( parse(text=("x+2")) )
}
print( f(2) )
4
I do not find an alternative way.
Thanks you
How about creating the function by pasting your string in as the body, then evaluating the whole thing?
str <- "x+2"
f <- eval(parse(text=paste("function(x) {",str,"}")))
f(2)
## 4
? That way the evaluation cost is paid once, up front, rather than every time the function is called ...
Another possibility is to create a function of x with an empty body, then fill in the parsed expression as the body ...
f <- function(x) {}
body(f) <- parse(text="x+2")
f(2)
By the way, I hope you're being careful about what strings you evaluate, e.g. what happens if str is something like "system('rm -rf /')" ... ?