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")
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))
Write csv with different separators in same df in R
With readr
you can use write_delim()
to output a file with comma-separated column names then call it a second time, without column names, and in append mode.
library(read)
mtcars[0, ] %>%
write_delim(file = "test.dat",delim = ',', col_names = TRUE)
mtcars %>%
write_delim(file = "test.dat",delim = ';', col_names = FALSE, append = TRUE)
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)
}
}
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.
Saving multiple data-frames to single csv file using Shiny downloadHandler
Other options:
- Write an Excel workbook with one sheet per
dataframe - 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)
}
)
}
)
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"))
}
write.csv() a list of unequally sized data.frames
That's a warning, not an error. You can't change append=FALSE
with write.csv
. ?write.csv
says:
Attempts to change ‘append’, ‘col.names’, ‘sep’, ‘dec’ or ‘qmethod’
are ignored, with a warning.
Use write.table
with sep=","
instead.
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.csv on a list of data frames
The problem is that the input x is a number not the element of a list.
Try
lapply(1:length(na_sx), function (x) write.csv(na_s[[x]],file = paste('./na_s_daily/','na_', names (na_s[x]),'.csv',sep=""), row.names = F))
Note that the above will also return a list of the data frames. So if you just need to save each element of the list as a data frame in your directory just do
for(x in 1:length(na_s)){
write.csv(na_s[[x]],file = paste('./na_s_daily/','na_',names (na_s[x]),'.csv',sep=""), row.names = F)
}
Related Topics
Extracting Data from Text Files
How to Swap Labels and Symbols in a Legend in R
Cannot Read File with "#" and Space Using Read.Table or Read.CSV in R
Contrasts Can Be Applied Only to Factor
Counting Occurrence of Particular Letter in Vector of Words in R
Differencebetween Aes and Aes_String (Ggplot2) in R
Importing Data into R (Rdata) from Github
Shiny Rcharts Multiple Chart Output
Extracting Indices for Data Frame Rows That Have Max Value for Named Field
Why Does Dplyr's Filter Drop Na Values from a Factor Variable
Car::Scatter3D in R - Labeling Axis Better
Download Plotly Using Downloadhandler
Rename Columns by Pattern in R
How to Define Fill Colours in Ggplot Histogram
How to Plot Bars and One Line on Two Y-Axes in the Same Chart, with R-Ggplot