access a nested list element from a vector of names specifying the path

Viewed 34

Hullo,

If I've got a function

foo <- function(list, name)

where I would want

foo(list, c("a", "b", "c"))

to return

list[[a]][[b]][[c]]

and also fail gracefully if list[[a]][[b]][[c]] doesn't exist,

How do I accomplish this ideally in base R?

1 Answers

We could use pluck

foo <- function(list, name) {
        purrr::pluck(list, !!! name)
}

-testing

> lst1 <- list(a = list(b = list(c = 1:2)), b = list(d = list(e = 1:5)))

> foo(lst1, c("a", "b", "c"))
[1] 1 2

Or simply in base R

foo <- function(list, name) {
     list[[name]]
}
>  foo(lst1, c("a", "b", "c"))
[1] 1 2
Related