【问题标题】:R: get element by name from a nested listR:从嵌套列表中按名称获取元素
【发布时间】:2015-01-11 18:11:04
【问题描述】:

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

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

列表中每个元素的名称都是唯一的。

我想仅通过名称从此类列表中获取一个元素,而不知道它的位置。

例子:

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

getByName(smth, "b2") = 5

我也不想使用unlist,因为真正的列表中有很多重元素。

【问题讨论】:

标签: r list extract nested-lists


【解决方案1】:

目前最好的解决方案如下:

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 发布它here

【讨论】:

    猜你喜欢
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    相关资源
    最近更新 更多