Writing CSV Files
in R
Learn how to export data frames to CSV files using write.csv() and readr::write_csv(): the essential skill for sharing and saving your R analyses.
What Is a CSV File?
A CSV (Comma-Separated Values) file is a plain text file where each line represents a row of data, and values within each row are separated by commas. It is the most common format for exchanging tabular data between programs.
Why Write CSV from R?
Starting Point: the Data Frame
Before you write a CSV, you need a data frame in R. A data frame is a table where each column is a variable and each row is an observation:
Core Function: write.csv()
write.csv() is the built-in base R function for writing data frames to CSV files. Its basic signature is:
Modern Alternative: readr::write_csv()
The readr package (part of the tidyverse) provides write_csv(): a faster, more predictable function with better defaults:
write.csv() vs write_csv()
| write.csv() | write_csv() | |
|---|---|---|
| Package | Base R (built-in) | readr (tidyverse) |
| Row Names | Included by default | Never included |
| Speed | Moderate | Fast |
| Encoding | System default | Always UTF-8 |
| Quotes | Quotes all strings | Quotes only when needed |
| Append Mode | Supported | append = TRUE |
Step-by-Step Workflow
Example 1: Basic Export
Write the students data frame to a file called "students.csv" using base R:
Example 2: Using readr::write_csv()
The same task with the readr package: cleaner syntax, better defaults:
Example 3: Advanced Options
Handle missing values and append to an existing file:
Understanding File Paths
Inside the Output File
Let's compare what write.csv() and write_csv() actually produce for the same data frame:
"1","Alice",17,92
"2","Bob",16,88
"3","Cara",17,95
Alice,17,92
Bob,16,88
Cara,17,95
The row.names Trap
Common Mistakes
Summary Reference
| Feature | write.csv() | write_csv() |
|---|---|---|
| Package | base R | readr |
| Row Names | Must set FALSE | Never included |
| NA Handling | Writes "NA" | Customizable via na |
| Append | Supported | append = TRUE |
| Quoting | Quotes all strings | Quotes only if needed |
| Encoding | System locale | UTF-8 always |
| Best For | Quick scripts, no deps | Tidyverse projects |
Question 1 of 5
Which argument should you set to FALSE in write.csv() to prevent R from adding an extra column of row numbers?
Question 2 of 5
What package must be loaded before you can use write_csv()?
Question 3 of 5
You run write.csv(df, "results.csv") without setting row.names = FALSE. What happens in the output file?
Question 4 of 5
Which of the following is an advantage of readr::write_csv() over base R's write.csv()?
Question 5 of 5
You want to add new rows to an existing CSV file without deleting the old data. Which function and argument combination achieves this?