[英]Aggregating data from lists inside lists
Below I will put my reproduceable example. 下面,我将展示我的可复制示例。 Right now when I am doing a bunch of regression type work across many different sources (say 50 things) I aggregate each one in a list and then combine those lists together for easy storage. 现在,当我在许多不同的来源(例如50件事)上进行大量回归类型工作时,我将每个集合汇总在一个列表中,然后将这些列表组合在一起以方便存储。 The structure is the same for each list, it just holds different data. 每个列表的结构相同,只是包含不同的数据。 What is the best way I can go about aggregating specific parts? 汇总特定部分的最佳方法是什么? In this example, whats the fastest way to combine ds1,ds2,ds3 & ds4, which are embedded into different lists? 在此示例中,结合嵌入不同列表的ds1,ds2,ds3和ds4的最快方法是什么?
set.seed(50)
df1 <- data.frame(x=runif(10),y=runif(10))
set.seed(50)
df2 <- data.frame(x=runif(10),y=runif(10))
set.seed(50)
df3 <- data.frame(x=runif(10),y=runif(10))
set.seed(50)
df4 <- data.frame(x=runif(10),y=runif(10))
rs1 <- rep(0.05,5)
rs2 <- rep(0.03,5)
rs3 <- rep(0.06,5)
rs4 <- rep(0.09,5)
ds1 <- rep(0.04,5)
ds2 <- rep(0.04,5)
ds3 <- rep(0.04,5)
ds4 <- rep(0.04,5)
rsdsList1 <- list(rs1,ds1)
rsdsList2 <- list(rs2,ds2)
rsdsList3 <- list(rs3,ds3)
rsdsList4 <- list(rs4,ds4)
mg1 <- list(df1,rsdsList1)
mg2 <- list(df2,rsdsList2)
mg3 <- list(df3,rsdsList3)
mg4 <- list(df4,rsdsList4)
You can collect, into a single list, the nth elements of multiple lists with: 您可以使用以下方法将多个列表的第n个元素收集到一个列表中:
lapply(list(mg1, mg2, mg3, mg4), '[[', n)
So in your case, lapply(list(mg1, mg2, mg3, mg4), '[[', 1)
will create the list that you're after. 因此,在您的情况下, lapply(list(mg1, mg2, mg3, mg4), '[[', 1)
将创建您想要的列表。
You can name the list elements that you iterate over with lapply
to have those names transferred to elements of the output list, eg 您可以使用lapply
命名迭代的列表元素,以将那些名称转移到输出列表的元素,例如
lapply(list(mg1=mg1, mg2=mg2, mg3=mg3, mg4=mg4), '[[', 1)
or wrap the lapply
in setNames
: 或将lapply
包装在setNames
:
setNames(lapply(list(mg1, mg2, mg3, mg4), '[[', 1), paste0('mg', 1:4))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.