Reputation: 521
I have a list of nested dataframes:
set.seed(1)
S1 = data.frame(replicate(2,sample(0:130,30,rep=TRUE)))
S2 = data.frame(replicate(2,sample(0:130,34,rep=TRUE)))
S3 = data.frame(replicate(2,sample(0:130,21,rep=TRUE)))
S4 = data.frame(replicate(2,sample(0:130,26,rep=TRUE)))
df_list1 = list(S1 = S1, S2 = S2, S3 = S3, S4 = S4)
set.seed(2)
S1 = data.frame(replicate(2,sample(0:130,30,rep=TRUE)))
S2 = data.frame(replicate(2,sample(0:130,34,rep=TRUE)))
S3 = data.frame(replicate(2,sample(0:130,21,rep=TRUE)))
S4 = data.frame(replicate(2,sample(0:130,26,rep=TRUE)))
df_list2 = list(S1 = S1, S2 = S2, S3 = S3, S4 = S4)
set.seed(3)
S1 = data.frame(replicate(2,sample(0:130,30,rep=TRUE)))
S2 = data.frame(replicate(2,sample(0:130,34,rep=TRUE)))
S3 = data.frame(replicate(2,sample(0:130,21,rep=TRUE)))
S4 = data.frame(replicate(2,sample(0:130,26,rep=TRUE)))
df_list3 = list(S1 = S1, S2 = S2, S3 = S3, S4 = S4)
set.seed(4)
S1 = data.frame(replicate(2,sample(0:130,30,rep=TRUE)))
S2 = data.frame(replicate(2,sample(0:130,34,rep=TRUE)))
S3 = data.frame(replicate(2,sample(0:130,21,rep=TRUE)))
S4 = data.frame(replicate(2,sample(0:130,26,rep=TRUE)))
df_list4 = list(S1 = S1, S2 = S2, S3 = S3, S4 = S4)
df_list = list (df_list1, df_list2, df_list3, df_list4)
names(df_list) = c("AB_df", "BC_df", "DE_df", "FG_df")
I want to extract the first column of every dataframe by a loop and save this into a list. My problem is now how to make the loop to save it correctly. Which running index do I have to use? I tried different versions, but nothing worked. This is my code and I need to know now what to use instead of ???
datalist = list()
for (a in 1:length(df_list)) {
for (b in 1:length(df_list[[1]])) {
datalist[[?????]] = df_list[[a]][[b]][1]}}
To make it more clear: As output I want a list containing every 1st column of all 16 dataframes. So 16 list entries.
Upvotes: 0
Views: 185
Reputation: 2718
purrr
works perfectly here.
library(purrr)
datalist <-
df_list %>%
# prepend top level names to dataframe names
imap(~ set_names(.x, function(nms) {paste(.y, nms, sep = "-")})) %>%
flatten() %>%
map(1)
Upvotes: 1