开发者

Accessing R list elements through function parameters

开发者 https://www.devze.com 2023-03-10 06:26 出处:网络
I have an R list which looks as follows > str(prices) List of 4 $ ID: int 102894616 $ delay: int 8 $ 47973:List of 12

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

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 acce开发者_开发百科ss function with signature:

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

Which can be used as follows:

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

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


Using '[[' instead of '$' seems to work:

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

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

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.


You can take advantage of the fact that [[ accepts a vector, used recursively:

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

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

精彩评论

暂无评论...
验证码 换一张
取 消