Home > Mobile >  Export dataframes from a list into a folder using write.csv
Export dataframes from a list into a folder using write.csv

Time:11-18

Edited for clarity and reproduciblity....

I have a list of dataframes that I want to export to a folder on my PC via a file path. Doing this one at a time, or writing multiple 'write.csv' commands is possible, but repetitive. Is there a way that I could use a for loop to export my data frames from that list using a single command?

example data:

m1 <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
               75, 10, 36, 36, 23, 55, 56, 24, 22, 66,
               -7.8, -5.6, -2, -4.1, -8.4, -3, -4.2, -4, 0.1, -3), nrow = 10) 
df <- as.data.frame(m1)  
split_n <- 5 
dlist <- split(df, factor(sort(rank(row.names(df))%%split_n))) 
names(dlist) <- paste0("site_data", 1980:1984)
dlist

I can do the following, one file at a time:

write.csv(dataList$table_1,"C:/filepath/dataframe_name_1.csv", row.names = F)

But doing this for hundreds of files isn't exactly efficient.

What I want to do is send the five data frames (site_data1980 : site_data1984) along my filepath to the folder on my PC as a list of named csv files.

CodePudding user response:

lapply(seq_along(dataList), \(i) write.csv(dataList[[i]], paste0("C:/filepath/dataframe_name_", i, ".csv"), row.names = F))

CodePudding user response:

You could try something like this

filepath <- "C:/filepath/dataframe_name_"

purrr::imap(dlist, ~write.csv(x = .x, file = paste0(filepath,  
                              readr::parse_number(.y), ".csv"), 
                              row.names = FALSE))
  • Related