Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
911 views
in Technique[技术] by (71.8m points)

parsing - R: eval(parse(...)) is often suboptimal

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)

So if eval(parse(...)) is suboptimal what is another way to do accomplish this?

I am calling some data from a website using RCurl, what i get after using fromJSON() in the rjson package is a list within a list. Part of the list has the name of an order number that will change depending on the order. The list looks something like:

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

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

I want to extract the value in $orders$'5810584'$price

Say the list is in the object dat. What I did to extract this using eval(parse(...)) was:

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

What would be a more optimal way of doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Actually the list probably looks a bit different. The '$' convention is somewhat misleading. Try this:

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

The '$' does not evaluate its arguments, but "[[" does, so or_ID will get turned into "5810584".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...