您可以使用以下递归函数,即使您的列表深度超过 2 级,该函数也可以使用
getElemsR <- function(dat, Index, Lev=2) {
if ((Lev <- (Lev - 1)) > 1) {
inds <- seq(length(dat[[1]]))
dat <- unlist(lapply(inds, function(i) getElemsR(dat, i, Lev)), recursive=F)
}
sapply(dat, "[[", Index, USE.NAMES=T, simplify=F)
}
# get the 2nd element of every 2nd-Level list
getElemsR(myData, 3) # Lev=2 by default
# get the 2nd element of every 3rd-Level list
getElemsR(myData, 2, 3)
# if needed as a vector:
unlist(getElemsR(myData, 2, 3))
或者,如果您的列表只有两层深,您可以使用简单的 sapply 正如@Romain 指出的那样。您可以将其包装在一个函数中
getElems <- function (dat, Index) {
sapply(dat, "[[", Index)
}
# get the 2nd element of every 2nd-level list
getElems(data1, 2)
样本数据
data1 <- lapply(1:3, paste0, c("A","B"))
data2 <- lapply(4:6, paste0, c("A","B"))
names(data1) <- names(data2) <- c("_sub1", "_sub2", "_sub3")
myData <- list(Lev1A=data1, Lev1B=data2)