本文介绍了通过函数参数访问R列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个R列表,看起来如下

I have an R list which looks as follows

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

很明显,我可以通过price $"47973" $ id.

Clearly, I can access any element by e.g. prices$"47973"$id.

但是,我将如何编写一个参数化对该列表的访问的函数?例如带有签名的访问功能:

However, how would I write a function which parametrises the access to that list? For example an access function with signature:

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

可用于以下用途:

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

这似乎很琐碎,但是我无法编写这样的函数.感谢您的指导.

This seems very trivial but I fail to write such a function. Thanks for any pointers.

推荐答案

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

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的元素,而不是该对象求值的对象.


As to why this works instead of:access <- function(index1, index2) prices$index1$index2 (which I assume is what you tried?) it's because here index1 and index2 are not evaluated. That is, it searches the list for an element called index1 instead of what this object evaluates to.

这篇关于通过函数参数访问R列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 01:53