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 this?

I call some data from a website using RCurl, what I get after using fromJSON() in the rjson package is a list in a list. Part of the list has the name of the order number, which will vary depending on the order. The list looks something like this:

 $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 a dat object. 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 better way to do this?

+8
r parsing
Jun 13 2018-12-12T00:
source share
1 answer

In fact, the list probably looks a little different. The '$' convention is somewhat misleading. Try the following:

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

"$" does not evaluate its arguments, but "[[" does ", so" or_ID "will turn into" 5810584 ".

+19
Jun 42--14 2018-12-12T00:
source share



All Articles