我有一个嵌套列表:
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
,因为实际列表中有很多重要元素。
我有一个嵌套列表:
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在这里发布。