[英]Processing nested lists in R
您已经在第一个lapply
遍历每个列表元素。 因此,根据您的结构,循环的每次迭代将包含2个元素( mu
和rooti
)的列表。 因此,您只需要一个lapply
:
ll <- list(list(mu = runif(15), root = runif(10)), list(mu = runif(15), runif(10)))
str(ll)
#List of 2
# $ :List of 2
# ..$ mu : num [1:15] 0.314 0.614 0.228 0.594 0.447 ...
# ..$ root: num [1:10] 0.73 0.496 0.266 0.599 0.917 ...
# $ :List of 2
# ..$ mu: num [1:15] 0.134 0.244 0.507 0.771 0.934 ...
# ..$ : num [1:10] 0.818 0.138 0.83 0.509 0.914 ...
lapply(ll, function(x) mean(x$mu))
#[[1]]
#[1] 0.4264001
#
#[[2]]
#[1] 0.4526724
您可以使用
hb.post.PT1$compdraw %>%
purrr::map(function(x) {
mean(x$mu)
}) %>% unlist
这就是我如何使用purrr::imap
做到的。 我们可以应用一个函数,该函数使用列表索引和该索引的mu
向量的均值创建tbl
,并将它们绑定到一个数据帧中以便于显示。
library(tidyverse)
set.seed(12345)
testlist <- list(
list(mu = rnorm(15), rooti = rnorm(15)),
list(mu = rnorm(15), rooti = rnorm(15)),
list(mu = rnorm(15), rooti = rnorm(15)),
list(mu = rnorm(15), rooti = rnorm(15)),
list(mu = rnorm(15), rooti = rnorm(15))
)
str(testlist[1:2])
#> List of 2
#> $ :List of 2
#> ..$ mu : num [1:15] 0.586 0.709 -0.109 -0.453 0.606 ...
#> ..$ rooti: num [1:15] 0.817 -0.886 -0.332 1.121 0.299 ...
#> $ :List of 2
#> ..$ mu : num [1:15] 0.812 2.197 2.049 1.632 0.254 ...
#> ..$ rooti: num [1:15] 1.461 -1.413 0.567 0.583 -1.307 ...
testlist %>%
imap_dfr(.f = ~ tibble(index = .y, mu_mean = mean(.x$mu)))
#> # A tibble: 5 x 2
#> index mu_mean
#> <int> <dbl>
#> 1 1 0.0341
#> 2 2 0.448
#> 3 3 0.146
#> 4 4 -0.130
#> 5 5 0.244
由reprex软件包 (v0.2.0)于2018-05-07创建。
在这种情况下可能会过大,但对于此类问题,通常最好记住有关purrr::transpose
map(transpose(hb.post.PT1$compdraw)$mu,mean)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.