How to Write Data Frames to CSV Files in R
Write data frames to CSV files in R using readr::write_csv() for clean UTF-8 output with no row names. Base R’s write.csv() adds a row-number column by default, so always set row.names = FALSE. For large datasets, data.table::fwrite() is 5-10x faster than the alternatives — benchmark your export if working with millions of rows.
library(readr)
write_csv(df, "output.csv")
readr::write_csv() writes NA as empty fields, compatible with most downstream tools. The na argument lets you specify a custom string for missing values, such as "N/A" or "missing".
# Base R — always set row.names = FALSE
write.csv(df, "output.csv", row.names = FALSE)
# data.table — fastest for large files
library(data.table)
fwrite(df, "output.csv")
Use write_csv() for general use, fwrite() when speed matters with millions of rows, and write.csv() only when base R is the sole option. To append to an existing CSV, use write_csv(df, "file.csv", append = TRUE). Control quoting behaviour with the quote argument — set it to "none" for output that omits quote characters around string fields. The col_names argument lets you suppress the header row when writing to a file that already has one.
See also
- data.frame, Base R data frame
- tibble, Tidyverse tibble
- How to Read a CSV and Summarise It, Related cookbook