R: get element by name from a nested list

2019-02-24 23:11发布

问题:

I have a nested list like so:

smth <- list()
smth$a <- list(a1=1, a2=2, a3=3)
smth$b <- list(b1=4, b2=5, b3=6)
smth$c <- "C"

The names of every element in the list are unique.

I would like to get an element from such a list merely by name without knowing where it is located.

Example:

getByName(smth, "c") = "C"

getByName(smth, "b2") = 5

Also I don't really want to use unlist since the real list has a lot of heavy elements in it.

回答1:

The best solution so far is the following:

rmatch <- function(x, name) {
  pos <- match(name, names(x))
  if (!is.na(pos)) return(x[[pos]])
  for (el in x) {
    if (class(el) == "list") {
      out <- Recall(el, name)
      if (!is.null(out)) return(out)
    }
  }
}

rmatch(smth, "a1")
[1] 1
rmatch(smth, "b3")
[1] 6

Full credit goes to @akrun for finding it and mbedward for posting it here