2012-06-13 27 views
8
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) 

因此,如果eval(parse(...))是次优的什么是另一种方法做到这一点?R:eval(parse(...))往往不是最理想的

我打电话给一个网站使用RCurl的一些数据,我在rjson软件包中使用fromJSON()后得到的是列表中的一个列表。部分清单中的订单号码的名称将根据订单而变化。该列表看起来是这样的:

$orders 
$orders$'5810584' 
$orders$'5810584'$quantity 
[1] 10 

$orders$'5810584'$price 
[1] 15848 

我想提取$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 

什么是这样做的更好的方法?

+5

dat $ orders [[or_ID]] $ price? – Dason

+0

不起作用,因为or_ID是一个字符而不是数字。 使用,dat $ orders [[1]] $ price可以工作 – Kevin

+0

使用'match'来获取名称在'names(dat $ orders)'中的位置。 – joran

回答

19

其实这个列表可能看起来有点不同。 '''公约有点误导。试试这个:

dat[["orders"]][[ or_ID ]][["price"]] 

的 '$' 不评价它的参数,但是 “[” 呢,所以 'or_ID' 将得到变成 “5810584”。

+0

这与@Dason的评论不一样吗?我理解你的观点:'[[''可以概括为'dat [[foo_ID]] [[or_ID]] [[bar_ID]]' –

+0

是真的。 'x [[“a”]]'是'x $ a'。我试图强调这一点,“[[”可以让您混合评估级别:使用引用的值或将被评估的符号。 x $ a形式主义是误导性的,因为它导致新用户认为可能会对“a”进行评估,而情况正好相反。 –

+3

或'dat [[c(“orders”,or_ID,“price”)]]' – hadley