1

I am developing an R script that numerically solves and plots 2 person simultaneous move non-cooperative games, where the user interactively supplies the player's payoff functions. Eventually this will be a shiny app, but for now I am using readline(). I am just wondering if there is a better way to have the user supply the payoff functions?

user_input <- readline(prompt="enter a function of x and y (e.g. x^2+y^2-x*y): ")
func_text <- paste0("as.function(alist(x=,y=,",user_input,"))")
the_func <- eval(parse(text=func_text))
print(paste0("the value of your function at (x,y)=(10,10) is: ",the_func(10,10)))

Bonus: how could I test that the supplied string-function is valid before eval?

1 Answers1

2

changing the function definition to this solves the issue

user_input <- "j"
while(!grepl("^([xy+/*-]|\\d)+$", user_input)) user_input <- readline(prompt="enter a function of x and y (e.g. x^2+y^2-x*y): ")
the_func <-  eval(parse(text=paste0("function(x,y) ",user_input)))

Following the comments by @AllanCameron and @stevec and the issues they raised it seems that input validation is a must that's what the while loop is there for.

Abdessabour Mtk
  • 3,895
  • 2
  • 14
  • 21