Mr.Spock
Mr.Spock

Reputation: 521

R - Saving every dataframe in a list of dataframes

I have this list of 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 save every single dataframe in this list (by write.table). I started to make a list of every single df-name:

level1 = paste("df_list", names(df_list), sep = "$")
samples = names(df_list[[1]])
df_names = paste(rep(level1, each = length(samples)), samples, sep = "$")

My idea is now to loop though this list and save the dataframe with write.table and automatically assign a name.

But my problem is that df_names[i] is a character and I cant use it as a df-path. Any idea?

Upvotes: 0

Views: 620

Answers (2)

makeshift-programmer
makeshift-programmer

Reputation: 499

You could write a nested for-loop as follows:

for(i in 1:length(df_list)){
  for(idx in 1:length(df_list[[i]])){
    write.table(df_list[[i]][[idx]],paste0("your_location",names(df_list[i]),"_",names(df_list[[i]][idx]),".csv"))
  }
}

Let me know if it works.

Upvotes: 1

Roland
Roland

Reputation: 132706

I'd flatten the list:

flatlist <- unlist(df_list, recursive = FALSE)
for (n in names(flatlist)) write.csv(flatlist[[n]], sprintf("%s.csv", n))

Upvotes: 1

Related Questions