我有这样的列表out
:
u <- list(a = list(b = 1, c = 2),
x = list(k = list(ka = 1, kb = 3),
l = list(la = 1, la = 4)))
v <- list(a = list(b = 1, c = 2),
x = list(m = list(ma = 5, mb = 8),
n = list(na = 5, nb = 8)))
w <- list(a = list(b = 1, c = 2),
x = list(o = list(oa = 4, ob = 1),
p = list(pa = 8, pb = 0)))
out <- list(u, v, w)
我想创建另一个列表,其中有元素k, l, m, n, o, p
,并保留列表元素的名称。我找到了一个解决方案,但看起来不是最佳的:
x <- lapply(out, function(y) y[['x']])
o <- list()
for (a in x) {
o <- c(o, a)
}
> str(o, max.level = 1)
List of 6
$ k:List of 2
$ l:List of 2
$ m:List of 2
$ n:List of 2
$ o:List of 2
$ p:List of 2
有更好的方法吗?
答案 0 :(得分:4)
循环可以替换为unlist
:
res <- unlist( lapply(out,"[[","x"), recursive=FALSE)
identical(res,o)
# [1] TRUE
我的lapply
与OP相同;它只是一条捷径。
正如@akrun建议的那样,你可以用
更密切地反映OP的循环do.call("c", lapply(out, '[[', 'x'))