我有一个嵌套数据框列表:
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")
我想通过循环提取每个数据帧的第一列,并将其保存到列表中。我的问题是现在如何使循环正确保存。我必须使用哪个运行索引?我尝试了不同的版本,但没有任何效果。这是我的代码,现在我需要知道使用什么而不是???
datalist = list()
for (a in 1:length(df_list)) {
for (b in 1:length(df_list[[1]])) {
datalist[[?????]] = df_list[[a]][[b]][1]}}
更清楚地说:作为输出,我想要一个包含所有16个数据帧的第一列的列表。因此有16个列表条目。
答案 0 :(得分:1)
purrr
在这里工作完美。
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)