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:
Syntax
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
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)
Login to try C/C++/Java/PHP code in the editor
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
- Forgetting
row.names = FALSE, which adds an unwanted index column to the CSV. - Overwriting an existing file without noticing, because
write.csvreplaces it silently. - 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: