好的,所以我正在运行一些循环来处理存储在列表对象中的数据.我fortune不记得臭名昭着的警告不要使用eval(parse(mystring)),我想到了这个:
Rgames> bar
$foo
$foo$fast
[1] 1 2 3 4 5
$foo$slow
[1] 6 7 8 9 10
$oof
$oof[[1]]
[1] 6 7 8 9 10
$oof[[2]]
[1] 1 2 3 4 5
Rgames> rab<-'bar'
Rgames> do.call('$',list(as.name(rab),'oof'))
[[1]]
[1] 6 7 8 9 10
[[2]]
[1] 1 2 3 4 5
Run Code Online (Sandbox Code Playgroud)
通常我会选择一个列表(其中bar一个是这样的),然后是列表中的一个元素(例如 oof),其中包含我的数据.上面的代码与之相同eval(parse(text=paste(rab,'$','oof',sep=''))).
我正在做这一切,因为我想使用列表的名称而不是[[x]]符号作为安全机制(因为并非所有列表对象的内容都以相同的顺序).我是否应该坚持使用D中的DWin的建议:eval(解析(...))通常不是最理想的?
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)
这样做的最佳方式是什么?