How to Write CSV Files in R: Simple Guide
In R, you can write data frames to CSV files using the
write.csv() function. Simply pass your data frame and the file name as arguments, like write.csv(data, "file.csv"). This saves your data in a CSV format that can be opened by spreadsheet programs.Syntax
The basic syntax of write.csv() is:
write.csv(x, file, row.names = TRUE, ...)
Where:
xis the data frame you want to save.fileis the name of the CSV file to create.row.namescontrols if row names are saved (default isTRUE)....allows extra options likenafor missing values.
r
write.csv(x, file, row.names = TRUE, ...)
Example
This example shows how to create a simple data frame and save it as a CSV file named example.csv. It demonstrates the basic use of write.csv().
r
data <- data.frame(Name = c("Anna", "Ben", "Cara"), Age = c(28, 34, 23)) write.csv(data, "example.csv", row.names = FALSE) # Check the file content by reading it back read.csv("example.csv")
Output
Name Age
1 Anna 28
2 Ben 34
3 Cara 23
Common Pitfalls
Some common mistakes when writing CSV files in R include:
- Forgetting to set
row.names = FALSEif you don't want row numbers saved as a separate column. - Using an invalid file path or lacking write permission causes errors.
- Not specifying
naparameter if you want missing values saved differently (default isNA).
r
## Wrong: row names saved as extra column write.csv(data, "wrong.csv") ## Right: exclude row names write.csv(data, "right.csv", row.names = FALSE)
Quick Reference
Here is a quick summary of important write.csv() options:
| Option | Description | Default |
|---|---|---|
| x | Data frame to write | Required |
| file | File name or path | Required |
| row.names | Include row names as first column | TRUE |
| na | String for missing values | "NA" |
| fileEncoding | File encoding (e.g., "UTF-8") | System default |
Key Takeaways
Use write.csv(data, "file.csv", row.names = FALSE) to save data frames without row numbers.
Always check file paths and permissions to avoid write errors.
Customize missing value representation with the na parameter if needed.
Reading the CSV back with read.csv helps verify the saved file.
write.csv is a simple and effective way to export data from R.