避免臭名昭著的“eval(parse())"构造 [英] Avoiding the infamous "eval(parse())" construct

查看:32
本文介绍了避免臭名昭著的“eval(parse())"构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在运行一些循环来处理存储在列表对象中的数据.记得臭名昭著的 fortune 告诫不要使用 eval(parse(mystring)),我想出了这个:

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

通常我会选择一个列表(其中 bar 就是其中之一),然后选择包含我的数据的列表中的一个元素(例如 oof).上面的代码与 eval(parse(text=paste(rab,'$','oof',sep=''))) 的作用相同.
我之所以这样做,是因为我想使用列表的名称而不是 [[x]] 符号作为安全机制(因为并非所有列表对象的内容都以相同的顺序排列).

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).

我应该坚持 DWin 在 R: eval(parse(...)) 往往是次优的 ?

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

推荐答案

使用 get[[:

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

这篇关于避免臭名昭著的“eval(parse())"构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆