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:
好的,所以我正在运行一些循环来处理存储在列表对象中的数据。我注意到臭名昭着的财富警告不要使用eval(解析(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
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 ?
通常我会选择一个列表(其中一个是这样的栏),然后是列表中的一个元素(例如oof),其中包含我的数据。上面的代码与eval完全相同(parse(text = paste(rab,'$','oof',sep ='')))。我正在做这一切,因为我想使用列表的名称而不是[[x]]表示法作为安全机制(因为并非所有列表对象的内容都以相同的顺序排列)。我应该坚持使用R中的DWin的建议:eval(解析(...))通常不是最理想的吗?
2 个解决方案
#1
14
Using get
and [[
:
使用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
#2
3
If the name of your top list is going to change and be accessed by a variable with the name then it is best to put those lists into another list, then you can access the list you want using [[
. Also read fortune(312)
and the help on ?'[['
.
如果您的*列表的名称将更改并由具有名称的变量访问,那么最好将这些列表放入另一个列表,然后您可以使用[[。还读了算命(312)和帮助?'[['。
You can then access the pieces in a different ways (detailed on the help page ?'[['
).
然后,您可以通过不同的方式访问这些部分(详情请参阅帮助页面?'[[')。
mylist <- list()
mylist$bar <- bar
mylist[[rab]][['oof']]
#or
mylist[[ c(rab,'oof') ]]
#1
14
Using get
and [[
:
使用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
#2
3
If the name of your top list is going to change and be accessed by a variable with the name then it is best to put those lists into another list, then you can access the list you want using [[
. Also read fortune(312)
and the help on ?'[['
.
如果您的*列表的名称将更改并由具有名称的变量访问,那么最好将这些列表放入另一个列表,然后您可以使用[[。还读了算命(312)和帮助?'[['。
You can then access the pieces in a different ways (detailed on the help page ?'[['
).
然后,您可以通过不同的方式访问这些部分(详情请参阅帮助页面?'[[')。
mylist <- list()
mylist$bar <- bar
mylist[[rab]][['oof']]
#or
mylist[[ c(rab,'oof') ]]