Save all data frames in list to separate .csv files

一笑奈何 提交于 2019-12-19 10:57:19

问题


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.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]]),...)


来源:https://stackoverflow.com/questions/34723202/save-all-data-frames-in-list-to-separate-csv-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!