Reputation: 2706
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. 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?
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)
Upvotes: 1
Views: 60
Reputation: 27388
You can collect, into a single list, the nth elements of multiple lists with:
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.
You can name the list elements that you iterate over with lapply
to have those names transferred to elements of the output list, e.g.
lapply(list(mg1=mg1, mg2=mg2, mg3=mg3, mg4=mg4), '[[', 1)
or wrap the lapply
in setNames
:
setNames(lapply(list(mg1, mg2, mg3, mg4), '[[', 1), paste0('mg', 1:4))
Upvotes: 2