我正在开发一个R脚本,它在数值上解决和绘制2人同时移动的非合作游戏,其中用户交互地提供玩家的支付函数。最终,这将是一个闪亮的应用程序,但现在我使用readline()。我只是想知道是否有更好的方法让用户提供支付函数?
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)))另外:如何在eval之前测试所提供的string-function是否有效?
发布于 2020-11-26 06:41:54
将函数定义更改为this可解决此问题
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)))在@AllanCameron和@stevec的评论和他们提出的问题之后,似乎输入验证是必须的,这就是while循环的作用。
https://stackoverflow.com/questions/65013628
复制相似问题