我有一个这样的嵌套列表:
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
,因为真正的列表中有很多重元素。
最佳答案
目前最好的解决方案如下:
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
关于R:从嵌套列表中按名称获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27890388/