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

Kev*_*vin 11 parsing r

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)

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

42-*_*42- 19

实际上,列表可能看起来有点不同."$"公约有点误导.试试这个:

dat[["orders"]][[ or_ID ]][["price"]]
Run Code Online (Sandbox Code Playgroud)

'$'不会评估其参数,但"[["确实如此,因此'or_ID'将变为"5810584".

  • 或者`dat [[c("orders",or_ID,"price")]]` (4认同)