2012-06-13 79 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