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
497 views
in Technique[技术] by (71.8m points)

r - Avoiding the infamous "eval(parse())" construct

Ok, so I'm running some loops to process data stored in list objects. Ever mindful of the infamous fortune admonishment not to use eval(parse(mystring)), I came up with this:

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

Typically I'd be selecting a list (of which bar is one such) and then one element of the list (e.g. oof) which contains my data. The code above does the same thing as eval(parse(text=paste(rab,'$','oof',sep=''))) .
I'm doing all this specifically because I want to use the lists' names rather than [[x]] notation as a safety mechanism (because not all list objects have their contents in the same order).

Should I stick with the advice from DWin in R: eval(parse(...)) is often suboptimal ?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Using get and [[:

bar <- list(foo = list(fast = 1:5, slow = 6:10),
            oof = list(6:10, 1:5))

rab <- 'bar'

get(rab)[['oof']]
# [[1]]
# [1]  6  7  8  9 10
# 
# [[2]]
# [1] 1 2 3 4 5

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

...