问题
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?
回答1:
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") )
回答2:
The mapply
function and its Map
wrapper are the multi-argument versions of lapply
. You have the list of data.frame
s; 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]]),...)
来源:https://stackoverflow.com/questions/34723202/save-all-data-frames-in-list-to-separate-csv-files