[英]Extract specific list elements from a nested list in R?
I have a nested list that looks like this:我有一个看起来像这样的嵌套列表:
x <- list(list(a = c(1,10), b=c(2,10)), list(c=c(3,10), d=c(6,10)), list(e= c(3,10)))
> x
[[1]]
[[1]]$a
[1] 1 10
[[1]]$b
[1] 2 10
[[2]]
[[2]]$c
[1] 3 10
[[2]]$d
[1] 6 10
[[3]]
[[3]]$e
[1] 3 10
Using nested sapply
-使用嵌套
sapply
-
sapply(x, function(y) sum(sapply(y, head, 1)))
#[1] 3 9 3
Or combine each list into a matrix and take sum
of first column/row.或者将每个列表组合成一个矩阵并取第一列/行的
sum
。
sapply(x, function(y) sum(do.call(rbind, y)[, 1]))
#sapply(x, function(y) sum(do.call(cbind, y)[1, ]))
Here's another option using a nested map_dbl
from purrr
:这是使用来自
purrr
的嵌套map_dbl
的另一个选项:
library(purrr)
map_dbl(x, ~sum(map_dbl(.x, 1)))
# [1] 3 9 3
A fast rapply
- vapply
approach.一种快速的
rapply
- vapply
方法。
vapply(rapply(x, \(x) unlist(`[`(x, 1)), how='list'), \(x) sum(unlist(x)), 0)
# [1] 3 9 3
## microbenchmark ##
# Unit: microseconds
# expr min lq mean median uq max neval cld
# sapply 124.166 128.4550 150.57375 131.5865 133.5845 2010.623 100 ab
# vapply 45.655 47.8645 84.40778 48.9600 49.7950 3583.235 100 a
# purrr 185.724 189.9295 194.47557 192.8915 195.6345 281.938 100 b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.