01 / 20

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.

R Programming

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.

R Data Frame name age score Alice 17 92 Bob 16 88 Cara 17 95 write.csv() data.csv name,age,score Alice,17,92 Bob,16,88 Cara,17,95

Why Write CSV from R?

★ Share Results
Send cleaned data to collaborators who may not use R.
★ Archive Data
Save processed data so you do not have to re-run your entire analysis.
★ Pipeline Integration
Feed your R output into other tools like Python, Tableau, or databases.

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:

# Create a simple data frame students <- data.frame( name = c("Alice", "Bob", "Cara"), age = c(17, 16, 17), score = c(92, 88, 95) )

Core Function: write.csv()

write.csv() is the built-in base R function for writing data frames to CSV files. Its basic signature is:

write.csv(x, file, row.names = TRUE, ...)
1
x: the data frame (or matrix) you want to export.
2
file: a string giving the path and filename, e.g. "output/results.csv".
3
row.names: logical. Set to FALSE to avoid writing row numbers as an extra column (almost always recommended).

Modern Alternative: readr::write_csv()

The readr package (part of the tidyverse) provides write_csv(): a faster, more predictable function with better defaults:

library(readr) write_csv(x, file, na = "NA", append = FALSE, ...)
✓ No Row Names
Never writes row names: no need to remember row.names = FALSE.
✓ Faster
Uses optimized C code: significantly faster on large data frames.
✓ UTF-8 Default
Always writes UTF-8 encoding, avoiding cross-platform encoding issues.

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

1
Prepare your data frame. Clean column names, remove unwanted rows, and ensure correct data types.
2
Choose your function. Use write_csv() from readr for modern projects, or write.csv() for base-R-only scripts.
3
Set the file path. Include the full or relative path and the .csv extension: "output/results.csv".
4
Disable row names (if using write.csv): set row.names = FALSE to get a clean file.
5
Verify the output. Open the file in a text editor or re-read it with read.csv() / read_csv() to confirm correctness.

Example 1: Basic Export

Write the students data frame to a file called "students.csv" using base R:

# Create the data students <- data.frame( name = c("Alice", "Bob", "Cara"), age = c(17, 16, 17), score = c(92, 88, 95) ) # Write to CSV (no row names) write.csv(students, "students.csv", row.names = FALSE)

Example 2: Using readr::write_csv()

The same task with the readr package: cleaner syntax, better defaults:

library(readr) students <- tibble( name = c("Alice", "Bob", "Cara"), age = c(17, 16, 17), score = c(92, 88, 95) ) # No need for row.names = FALSE! write_csv(students, "students.csv")

Example 3: Advanced Options

Handle missing values and append to an existing file:

library(readr) results <- tibble( student = c("Dan", "Eve"), grade = c(85, NA) ) # Write with custom NA string write_csv(results, "grades.csv", na = "missing") # Append more rows to an existing file new_rows <- tibble( student = "Frank", grade = 91 ) write_csv(new_rows, "grades.csv", append = TRUE)
na = "missing"
Replaces NA values with the string "missing" in the output file.
append = TRUE
Adds rows to the end of an existing file without overwriting it.

Understanding File Paths

my_project/ script.R output/ results.csv Relative path: "output/results.csv" Same folder: "results.csv"

Inside the Output File

Let's compare what write.csv() and write_csv() actually produce for the same data frame:

✕ write.csv() with defaults
"","name","age","score"
"1","Alice",17,92
"2","Bob",16,88
"3","Cara",17,95
✓ write_csv()
name,age,score
Alice,17,92
Bob,16,88
Cara,17,95

The row.names Trap

row.names = TRUE (default) "","name","age","score" "1","Alice",17,92 "2","Bob",16,88 "3","Cara",17,95 Extra column! row.names = FALSE name,age,score Alice,17,92 Bob,16,88 Cara,17,95 ✓ Clean output

Common Mistakes

✕ Forgetting row.names
Using write.csv(df, "file.csv") without row.names = FALSE adds an unwanted numeric column.
✕ Wrong File Extension
Naming the file "data.txt" instead of "data.csv". The data will be correct, but other tools may not recognize it.
✕ Overwriting Silently
Both functions overwrite existing files without warning. Always double-check the file path before running.
✕ Mixing Up Functions
Calling write_csv() without loading the readr package first produces an error: "could not find function".

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?