2011-06-05 56 views
3

我具有R列表,它看起来访问通过函数R列表元素参数

> str(prices) 
List of 4 
$ ID : int 102894616 
$ delay: int 8 
$ 47973  :List of 12 
    ..$ id  : int 47973 
    ..$ index  : int 2 
    ..$ matched: num 5817 
$ 47972  :List of 12 
.. 

显然如下,我可以通过例如访问任何元件价格$ “47973” 的$ id。

但是,我将如何编写一个函数来参数化访问该列表?例如与签名的接入功能:它可以如如下使用

access <- function(index1, index2) { .. } 

> access("47973", "matched") 
5817 

这看起来很琐碎,但我不写这样的功能。感谢任何指针。

回答

4

使用'[['而不是'$'似乎工作:

prices <- list(
    `47973` = list(id = 1, matched = 2)) 

access <- function(index1, index2) prices[[index1]][[index2]] 
access("47973","matched") 

至于为什么这个作品,而不是: access <- function(index1, index2) prices$index1$index2(我以为是你试过吗?)那是因为这里index1index2是没有评估。也就是说,它在列表中搜索名为index1的元素,而不是此对象的计算结果。

+0

谢谢,成功了! – jk3000 2011-06-05 13:15:56

+0

非常好,我开始认为这是无法解决的。 – Docconcoct 2017-10-11 18:41:15

3

你可以采取的事实,即[[接受的载体,递归使用:

prices <- list(
    `47973` = list(id = 1, matched = 2)) 

prices[[c("47973", "matched")]] 
# 2 
+0

谢谢,有用的知道。 – jk3000 2011-06-07 09:54:22