2

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

2
  • 1
    If you provide more context it's possible people could come up with some solutions that would fit. E.g., why doesn't this suit your needs? Commented Jun 15, 2018 at 2:25
  • 4
    I have problems in shiny. I am transforming a text into a function: f <- function(x){eval(parse ( text=( input$text ))) },but when I execute the code it takes time to do the calculations. If instead of transforming the "text into function", I write the function directly, then I have no problems. Commented Jun 15, 2018 at 2:30

2 Answers 2

4

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 /')" ... ?

Sign up to request clarification or add additional context in comments.

Comments

1

I might have totally missed your point, but here's what I've got for you:

f1 <- function(x="x") {
  a <- as.expression(paste0(x,"+2"))
  print(class(a))
  return( eval(parse(text=a)) )
}
f1(2)

4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.