【问题标题】:Accessing R list elements through function parameters通过函数参数访问 R 列表元素
【发布时间】:2011-06-05 11:25:14
【问题描述】:

我有一个如下所示的 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

这似乎很琐碎,但我没有编写这样的函数。感谢您的任何指点。

【问题讨论】:

    标签: list r syntax


    【解决方案1】:

    使用'[[' 代替'$' 似乎可行:

    prices <- list(
        `47973` = list( id = 1, matched = 2))
    
    access <- function(index1, index2) prices[[index1]][[index2]]
    access("47973","matched")
    

    至于为什么这有效,而不是: access &lt;- function(index1, index2) prices$index1$index2(我认为这是您尝试过的?)这是因为这里 index1index2 没有被评估。也就是说,它在列表中搜索名为 index1 的元素,而不是该对象的求值结果。

    【讨论】:

    • 太好了,我开始认为没有办法解决这个问题。
    【解决方案2】:

    您可以利用 [[ 接受一个向量,递归使用这一事实:

    prices <- list(
        `47973` = list( id = 1, matched = 2))
    
    prices[[c("47973", "matched")]]
    # 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 2017-02-03
      • 2021-06-15
      • 1970-01-01
      相关资源
      最近更新 更多