R:eval(解析(...))通常不是最理想的

时间:2012-06-13 23:54:37

标签: r parsing

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(...))不是最理想的,那么另一种方法是什么呢?

我使用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

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:19)

实际上这个列表可能看起来有点不同。 “$”公约有点误导。试试这个:

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

'$'不评估其参数,但“[[”确实如此,因此or_ID将变为“5810584”。