R:从嵌套列表中按名称获取元素 [英] R: get element by name from a nested list

查看:72
本文介绍了R:从嵌套列表中按名称获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的嵌套列表:

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.

示例:

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

getByName(smth, "b2") = 5

我也不希望使用unlist,因为实际列表中包含很多繁重的元素.

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

推荐答案

到目前为止,最佳的解决方案是:

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

全额荣誉归@akrun查找, mbedward 发布

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

这篇关于R:从嵌套列表中按名称获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆