我有一个 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
这看起来很微不足道,但我无法编写这样的函数。感谢您的指点。
Using '[['
代替'$'
似乎有效:
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
(我认为这是你尝试过的?)这是因为这里index1
and index2
不予评价。也就是说,它在列表中搜索名为的元素index1
而不是这个对象的计算结果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)