← Back to R Course | Chapter 8: Data Manipulation | Lesson 2 of 7

Writing Files

Writing files saves your results from R onto your computer, like saving a document after you finish it. You can store a data frame as a CSV that other programs can open.

In this page:

  1. Writing Files
Syntax
r
write.csv(df, "file.csv", row.names = FALSE)

Writing Files

write.csv(df, "file.csv") writes a data frame out to a CSV file, and row.names = FALSE is commonly added to avoid writing an extra unnamed index column.

This is the standard way to export processed data from R for use elsewhere. writeLines() is a lower-level alternative for writing plain text.

Note: Always pass row.names = FALSE to write.csv() unless you specifically want R's row index written as an extra column.

Example: Writing Files

markup
df <- data.frame(name = c("Alice", "Bob"), age = c(30, 25))

write.csv(df, "output.csv", row.names = FALSE)

contents <- readLines("output.csv")
print(contents)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting row.names = FALSE, which adds an unwanted index column to the CSV.
  2. Overwriting an existing file without noticing, because write.csv replaces it silently.
  3. Writing to a folder that does not exist, which fails with cannot open the connection.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.