我很想知道R是否可以使用它的eval()功能来执行例如字符串提供的计算.
这是一个常见的情况:
eval("5+5")
Run Code Online (Sandbox Code Playgroud)
但是,而不是10我得到:
[1] "5+5"
Run Code Online (Sandbox Code Playgroud)
有解决方案吗
require('fortunes')
fortune('106')
Personally I have never regretted trying not to underestimate my own future stupidity.
-- Greg Snow (explaining why eval(parse(...)) is often suboptimal, answering a question triggered
by the infamous fortune(106))
R-help (January 2007)
Run Code Online (Sandbox Code Playgroud)
那么,如果eval(parse(...))不是最理想,另一种方法是什么呢?
我使用RCurl从网站调用一些数据,我fromJSON()在rjson包中使用后得到的是列表中的列表.部分列表具有将根据订单更改的订单号的名称.该列表看起来像:
$orders
$orders$'5810584'
$orders$'5810584'$quantity
[1] 10
$orders$'5810584'$price
[1] 15848
Run Code Online (Sandbox Code Playgroud)
我想提取值 $orders$'5810584'$price
假设列表在对象中dat.我使用的方法eval(parse(...))是:
or_ID <- names(dat$orders) # get the order ID number
or_ID
"5810584"
sell_price <- eval(parse(text=paste('dat$',"orders$","'", or_ID, "'", "$price", sep="")))
sell_price
15848
Run Code Online (Sandbox Code Playgroud)
这样做的最佳方式是什么?
我期待在循环中分配对象.我已经读过某些形式的eval(parse(东西,我需要执行此操作,但我遇到错误列表invalid text或no such file or directory.下面是我试图做的一般示例代码:
x <- array(seq(1,18,by=1),dim=c(3,2,3))
for (i in 1:length(x[1,1,])) {
eval(parse(paste(letters[i],"<-mean(x[,,",i,"])",sep="")
}
Run Code Online (Sandbox Code Playgroud)
当我完成使用这些对象时,我想删除它们(实际的对象非常大,以后会导致内存问题......)
for (i in 1:length(x[1,1,])) eval(parse(paste("rm(",letters[i],")",sep="")))
Run Code Online (Sandbox Code Playgroud)
eval(parse(paste(此脚本的两个部分都返回invalid text或的错误no such file or directory.我在使用中遗漏了什么eval(parse(?是否有更简单/更好的方法在循环中分配对象?