R中的函数-使用eval()和parse()在rgl中绘制表达式

乔希

我对R非常陌生。我正在尝试创建一个函数,用户可以在其中将表达式输入到参数中。这些输入然后通过rgl包在plot3d中使用。到目前为止,我拥有的功能是:

flight_sim <- function(xval, yval, zval)
{
# Evaluate arguments and convert them into expressions 
eval(parse(text = zval))
z <- data.frame(zval)
eval(parse(text = xval))
x <- data.frame(xval)
eval(parse(text = yval))
y <- data.frame(yval)
flight_path <- as.data.frame(cbind(x,y,z))
}

我有一个readline()和switch()命令:

cat('Select the flight path you wish to plot from the list below : 
1. Helix
2. Conical
3. Spherical
4. Define your own flight path...')

userplot <- readline('Enter number here : ') # Allow user to enter choice from above

switch(userplot,"1"=flight_sim( sin(z), 1-cos(z), seq(0,20, pi/32) ),
                "2"=flight_sim( z*cos(6*z), z*sin(6*z), seq(0,10, pi/64) ),
                "3"=flight_sim( sin(z)*cos(20*z), sin(z)*sin(20*z), seq(0,pi,pi/399)), 
                "4"=custom())

其中custom()仅通过readline()提示用户输入x,y和z值,然后在其后跟随eval()和parse()即可正常工作。

我一直遇到的问题是x和y必须是z的函数,这会导致错误:

Error in parse(text = xval) : object 'z' not found

我认为通过使flight_sim函数首先评估zval参数可以解决该问题,但是由于我是R的新手,所以我越来越迷路了。

我希望我在这里所作的解释是有道理的。感谢提供的任何帮助。

弗里克先生

在您的示例中,没有任何内容作为文本传递,因此parse()似乎没有必要使用。如果要延迟评估,最好的方法是使用substitute按承诺获取参数,然后在fliht_sim函数的上下文中对它们进行评估这是什么样子

flight_sim <- function(xval, yval, zval) {
    z <- eval(substitute(zval))
    x <- eval(substitute(xval))
    y <- eval(substitute(yval))
    data.frame(x,y,z)
}


userplot="2"

x <- switch(userplot,"1"=flight_sim( sin(z), 1-cos(z), seq(0,20, pi/32) ),
                "2"=flight_sim( z*cos(6*z), z*sin(6*z), seq(0,10, pi/64) ),
                "3"=flight_sim( sin(z)*cos(20*z), sin(z)*sin(20*z), seq(0,pi,pi/399)), 
                "4"=custom())
head(x)
#            x          y          z
# 1 0.00000000 0.00000000 0.00000000
# 2 0.04697370 0.01424932 0.04908739
# 3 0.08162934 0.05454298 0.09817477
# 4 0.09342212 0.11383519 0.14726216
# 5 0.07513972 0.18140332 0.19634954
# 6 0.02405703 0.24425508 0.24543693

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章