我正在尝试将列表列表转换为组成矩阵。该代码有效,但我确定有更好的方法。感谢您的帮助。
#create list of lists
theta <- list()
for(k in 1:10){
theta[[k]] <- list(
alpha=rnorm(n=3,mean=0,sd=2),
mu=rnorm(n=3,mean=0,sd=2),
sd=rnorm(n=3,mean=0,sd=2))
}
#extract parts
alpha_out <- theta[[1]]$alpha
mu_out <- theta[[1]]$mu
sd_out <- theta[[1]]$sd
for(k in 2:length(theta)){
alpha_out <- rbind(alpha_out,theta[[k]]$alpha)
mu_out <- rbind(mu_out,theta[[k]]$mu)
sd_out <- rbind(sd_out,theta[[k]]$sd)
}
答案 0 :(得分:1)
您可以像这样使用sapply
:
alpha_out <- t(sapply(theta, function(x) {x$alpha}))
alpha_out <- t(sapply(theta, `[[`, 1))
答案 1 :(得分:1)
如果您想将alpha
,mu
和sd
分开,我们可以使用tranpose
中的purrr
library(purrr)
transpose(theta) %>% map(dplyr::bind_cols)
#$alpha
# A tibble: 3 x 10
# V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 1.65 0.295 0.145 -0.207 -0.857 -1.20 -0.665 4.19 1.20 -2.60
#2 -0.578 3.12 -2.14 0.798 0.946 0.0866 -0.217 1.86 0.147 -0.610
#3 2.42 0.804 1.72 2.14 -1.85 0.604 1.84 0.968 -1.51 -1.09
#$mu
# A tibble: 3 x 10
# V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 -0.0152 -2.34 -1.26 1.04 1.70 1.22 -3.01 1.80 -1.43 0.548
#2 -4.59 -0.917 -0.164 -0.384 1.09 0.259 0.265 2.55 -0.0560 -3.18
#3 0.616 1.02 -0.707 3.86 -1.73 2.15 -2.91 -2.30 -1.65 -1.43
#$sd
# A tibble: 3 x 10
# V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 -3.03 -0.705 1.10 -2.29 2.95 1.91 0.548 -2.08 -2.72 -2.93
#2 2.59 3.91 -1.05 2.76 3.41 1.25 -0.291 -2.30 -1.48 2.70
#3 0.242 -0.860 3.31 -4.19 -0.639 -0.720 -0.983 0.0544 2.00 0.939