Writing Multiple Data Frames into .CSV Files Using R

Writing multiple data frames into .csv files using R

Here's a self-contained example along the lines of Richard's comment, but uses the names of the dataframes in the list as filenames for the CSV files:

# Create a list of n data frames

n <- 10

my_list <- lapply(1:n, function(i) data.frame(x = rnorm(10), y = rnorm(10)) )

# name the data frames

names(my_list) <- letters[1:n]

# save each new data frame as an individual .csv file based on its name

lapply(1:length(my_list), function(i) write.csv(my_list[[i]],
file = paste0(names(my_list[i]), ".csv"),
row.names = FALSE))

Export multiple data frames into .csv files using R

Iterate over the data frame names. We assume all names start with d and are of length 3. Modify the pattern if not or directly set nms if you know them. We also make a second check that the names are data frames but you can omit that check if you are sure that there are no objects that are not data frames and have a name matching the pattern.

nms <- ls(pattern = "^d..$")
for(nm in nms) {
X <- get(nm)
if (is.data.frame(X)) {
filename <- paste0(nm, ".csv")
message("writing out ", filename)
write.csv(X, file = filename, row.names = FALSE)
}
}

Write different data frame in one .csv file with R

write.csv just calls write.table under the hood, with appropriate arguments. So you can achieve what you want with 3 calls to write.table.

write.table(df1, "filename.csv", col.names=TRUE, sep=",")
write.table(df2, "filename.csv", col.names=FALSE, sep=",", append=TRUE)
write.table(df3, "filename.csv", col.names=FALSE, sep=",", append=TRUE)

Actually, you could avoid the whole issue by combining your data frames into a single df with rbind, then calling write.csv once.

write.csv(rbind(df1, d32, df3), "filename.csv")

How to write multiple .csv files from a list of data frames into a new folder with the original filename?

Given that points_calculated is a list of data.frames, and the names(points_calculated) are the filename you want, you can do the following:

library(purrr)
points_calculated %>%
iwalk(
~ readr::write_csv(.x, file = paste("./ExperimentFolder/PointsFolder", .y))
)
)

imap() will iterate over your list, and perform the function after ~. .x is the element of the list (the data.frame), and .y is it's name.

Write multiple data frames to csv-file using purrr::map

map() and walk() both work, but walk() doesn't print anything, whereas map() will.

Invisible output

list(iris = iris, mtcars = mtcars) %>%
names(.) %>%
walk(~ write_csv(dfs[[.]], paste0("data-raw/", ., ".csv")))

Prints output to console

list(iris = iris, mtcars = mtcars) %>%
names(.) %>%
map(~ write_csv(dfs[[.]], paste0("data-raw/", ., ".csv")))

Write data frame to multiple csv's in R


# Split dataframe by city
split_df <- split(df, list(df$city))

# Write out separate CSV for each city
for (city in names(split_df)) {
write.csv(split_df[[city]], paste0(city, ".csv"))
}

Saving multiple data-frames to single csv file using Shiny downloadHandler

Other options:

  1. Write an Excel workbook with one sheet per
    dataframe
  2. Zip together multiple csv
    files

Here's a sample of both options using four dataframes from the R Datasets Package.

library(shiny)
library(xlsx)

shinyApp(
ui = fluidPage(
downloadButton("downloadExcelSheet", "Download Excel Workbook with Multiple Sheets"),
downloadButton("downloadZippedCSV", "Download zipped csv files")
),
server = function(input, output) {

#### Write an Excel workbook with one sheet per dataframe ####
output$downloadExcelSheet <- downloadHandler(
filename = function() {
"excelWorkbook.xlsx"
},
content = function(file) {
# write workbook and first sheet
write.xlsx(mtcars, file, sheetName = "mtcars", append = FALSE)

# add other sheets for each dataframe
listOtherFiles <- list(iris = iris,
airquality = airquality,
sleep = sleep)
for(i in 1:length(listOtherFiles)) {
write.xlsx(listOtherFiles[i], file,
sheetName = names(listOtherFiles)[i], append = TRUE)
}
}
)

#### Zip together multiple csv files ####
output$downloadZippedCSV <- downloadHandler(
filename = function() {
"zippedCSV.zip"
},
content = function(file) {
# go to temp dir to avoid permission issues
owd <- setwd(tempdir())
on.exit(setwd(owd))

# create list of dataframes and NULL value to store fileNames
listDataFrames <- list(mtcars = mtcars,
iris = iris,
airquality = airquality,
sleep = sleep)
allFileNames <- NULL

# loop through each dataframe
for(i in 1:length(listDataFrames)) {
# write each dataframe as csv and save fileName
fileName <- paste0(names(listDataFrames)[i], ".csv")
write.csv(listDataFrames[1], fileName)
allFileNames <- c(fileName, allFileNames)
}

# write the zip file
zip(file, allFileNames)

}
)
}
)

How to export multiple .csv-files?

ls() has pattern argument to get the object name based on specific pattern in the data. You may try -

my_list <- ls(pattern = '^data')

purrr::imap(mget(my_list),
~write.csv(.x, sprintf('data_%s.csv', .y), row.names = FALSE))

To keep it completely in base R -

tmp <- mget(my_list)
Map(function(x, y) write.csv(x, y, row.names = FALSE), tmp,
sprintf('data_%s.csv', names(tmp)))

where mget returns a named list of dataframes.



Related Topics



Leave a reply



Submit