从嵌套列表中按名称获取元素

3

我有一个嵌套列表:

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,因为实际列表中有很多重要元素。


1
请查看此链接http://r.789695.n4.nabble.com/How-to-get-a-specific-named-element-in-a-nested-list-td3037430.html。 - akrun
1个回答

5
到目前为止,最好的解决方案如下:
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在这里发布。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接