R: get element by name from a nested list

Deadly 提交于 2019-11-28 14:04:57

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

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