1

Rookie question but I can't find anywhere the answer. I need an input for example x^3-9*x

For example, I'm writing an interactive application where the user is prompted to input a symbolic expression for a function:

f=readline(prompt="A symbolic / mathematical function:")

then, the input from the console could be: x^3-9*x

I need to make the program understand that f is a function not just characters.

eduardokapp
  • 1,612
  • 1
  • 6
  • 28
DuckOc
  • 15
  • 3
  • Perhaps [this](https://stackoverflow.com/a/66928067/13513328) helps – Waldi Apr 19 '21 at 15:25
  • The latter, I want them to input something through the console like x^3-9*x , so that the user doesn't have to manually write the function after what you just wrote. – DuckOc Apr 19 '21 at 15:29
  • That's not necessarily a beginner or basic topic in R. Can they only use "x" as the variable? Other variables? This can become tricky for you in a hurry –  Apr 19 '21 at 15:37
  • The user will know to only input "x" as variable and no other, also the functions will be no more complicated than the mentioned. – DuckOc Apr 19 '21 at 15:44
  • You could take a look at this question: https://stackoverflow.com/questions/1743698/evaluate-expression-given-as-a-string But be careful, I don't recommend using `eval(parse(...))`. Bad things can happen... – Martin Gal Apr 19 '21 at 16:03

1 Answers1

2

You can create a wrapper around readline() that captures the string input and then creates a function. Here is an example using rlang. The single argument x is hard coded in, but this could be made to be more advanced.

readline_fn_x <- function(prompt) {
  
  fn_str <- readline(prompt = prompt)
  rlang::new_function(rlang::pairlist2(x = ), rlang::parse_expr(fn_str))
  
}

This will return a function. Here it is evaluated at f(2)

> f <- readline_fn_x(prompt="A function pls:")
A function pls:x^3-9*x
> f(2)
[1] -10