R: get element by name from a nested list

怎甘沉沦 提交于 2019-11-27 08:07:01

问题


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



来源:https://stackoverflow.com/questions/27890388/r-get-element-by-name-from-a-nested-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!