Save all data frames in list to separate .csv files
Asked Answered
L

2

5

I have a list of data frames that I want to save to independent .csv files.

Currently I have a new line for each data frame:

write.csv(lst$df1, "C:/Users/.../df1")
write.csv(lst$df2, "C:/Users/.../df2")
ad nauseam

Obviously this isn't ideal: a change in the names would mean going through every case and updating it. I considered using something like

lapply(lst, f(x) write.csv(x, "C:/Users/.../x") 

but that clearly won't work. How do I save each data frame in the list as a separate .csv file?

Larynx answered 11/1, 2016 at 13:51 Comment(0)
L
6

You can do this:

N <- names(lst)
for (i in seq_along(N)) write.csv(lst[[i]], file=paste0("C:/Users/.../"), N[i], ".csv")

Following the comment of Heroka a shorter version:

for (df in names(lst)) write.csv(lst[[df]], file=paste0("C:/Users/.../"), df, ".csv")

or

lapply(names(lst), function(df) write.csv(lst[[df]], file=paste0("C:/Users/.../"), df, ".csv") )
Laclair answered 11/1, 2016 at 13:58 Comment(1)
As you can also access list items by name, you could even iterate over the names themselves.Potage
H
3

The mapply function and its Map wrapper are the multi-argument versions of lapply. You have the list of data.frames; you need to build a vector of file names. Like this:

filenames<-paste0("C:/Users/.../",names(lst), ".csv")
Map(write.csv,lst,filenames)

What Map does? It calls the function provided as first argument multiple times and in each iteration its arguments are taken from the elements of the other arguments provided. Something on the line of:

list(write.csv(lst[[1]],filenames[[1]]),write.csv(lst[[2]],filenames[[2]]),...)
Hugohugon answered 11/1, 2016 at 14:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.