1

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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

amazing, this is exactly what I needed. what's the "!!!" for?
@mitmonghi that was done to evaluate to get the value in 'name'
@mitmonghi you can get more info about the splice operator with ?"!!!". Updated the base R option
ya know what, I never knew the [[ function actually just works exactly like what I wanted. I'd assumed it didn't work that way. Note that the base R solution doesn't work with a mix of numeric indexes and names, i.e. foo(lst1, c(1, "b", "c") doesnt work while pluck does
@mitmonghi that is true, because c converts it to a single type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.