jk3000
jk3000

Reputation: 163

Accessing R list elements through function parameters

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

Upvotes: 3

Views: 1701

Answers (2)

hadley
hadley

Reputation: 103948

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

Upvotes: 3

Sacha Epskamp
Sacha Epskamp

Reputation: 47612

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.

Upvotes: 5

Related Questions