Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: get element by name from a nested list

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.

like image 401
Karolis Koncevičius Avatar asked Dec 19 '25 20:12

Karolis Koncevičius


1 Answers

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

like image 177
Karolis Koncevičius Avatar answered Dec 22 '25 12:12

Karolis Koncevičius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!