尝试使用eval(parse(text=...))
或eval(substitute(...))
。
parse(text=...)
将字符串转换为表达式,eval
计算表达式。一定要使用text
参数,因为parse
通常会寻找文件。忽略这点是常见的错误。另请参阅?parse
和?eval
。
> a <- 10
> x <- deparse(substitute(a))
> eval(parse(text=x))
[1] 10
为了展示如何使用它,你需要调整你的代码:
for(i in 1:10)
eval(parse(text=paste("rp.slider(rpplot,param",i,")",sep="")))
substitute
函数会将语言对象中的值替换为第二个参数所给定的字符串:
for(i in 1:10)
eval(
substitute(
rp.slider(rpplot,x),
list(x=as.name(paste("param",i,sep="")))
)
)
或者,使用帮助文件中的示例:
library(rpanel)
rpplot <- rp.control(title = "Demonstration of rp.tkrplot", h = 1,j=1)
redraw <- function(panel) {
rp.tkrreplot(panel, tkrp)
}
x <- c('h','j')
rp.tkrplot(rpplot, tkrp, function(panel) plot((1:20)^panel$j, (1:20)^panel$h))
eval(parse(text=paste("rp.slider(rpplot, ",x[1]," , action = redraw,
from = 0.05, to = 2.00, resolution = 0.05)")))
eval(
substitute(
rp.slider(rpplot, x, action=redraw, from=0.05, to=2.00, resolution=0.05),
list(x = as.name(x[2]))
)
)
这是必要的原因可以在rp.slider的源代码中找到。函数内获取变量名的构造不是R中使用的标准构造。事实上,由于这个原因,“deparse(substitute())”的使用被强烈反对。对于大多数函数来说,
as.expression("x")
可以用于使用变量名获取变量。然而,rpanel软件包的作者却使这种方式不可能。
deparse(substitute(x))
返回[1] "x"
- 我想要一种从字符串返回相同输出的方法,即foo
对于输入deparse(substitute(foo("x")))
输出[1] "x"
的方式是什么?这可能吗? - daveslantedplyr
函数族是另一个可行的选择。我还喜欢failwith
选项,它为当特定绘图不按预期工作时提供了故障保护。 - Chase