0
0
R Programmingprogramming~5 mins

read.csv and write.csv in R Programming

Choose your learning style9 modes available
Introduction

We use read.csv to load data from a CSV file into R. We use write.csv to save data from R into a CSV file. This helps us work with data easily.

You want to analyze data stored in a CSV file on your computer.
You have created or changed data in R and want to save it for later or share it.
You want to move data between R and other programs like Excel.
You want to quickly check or edit data outside R using a spreadsheet.
You want to automate data processing by reading and writing CSV files in scripts.
Syntax
R Programming
read.csv(file, header = TRUE, sep = ",", stringsAsFactors = FALSE)
write.csv(x, file, row.names = TRUE)

file is the path to your CSV file.

header = TRUE means the first row has column names.

Examples
Reads a CSV file named data.csv with headers and default comma separator.
R Programming
data <- read.csv("data.csv")
Saves the data object to output.csv without row numbers.
R Programming
write.csv(data, "output.csv", row.names = FALSE)
Reads a CSV file without headers and uses semicolon as separator.
R Programming
data <- read.csv("data.csv", header = FALSE, sep = ";")
Sample Program

This program creates a small table with names and ages, saves it to people.csv, then reads it back and prints it.

R Programming
my_data <- data.frame(Name = c("Anna", "Bob"), Age = c(28, 34))
write.csv(my_data, "people.csv", row.names = FALSE)
loaded_data <- read.csv("people.csv")
print(loaded_data)
OutputSuccess
Important Notes

Always check the file path is correct when reading or writing files.

Use row.names = FALSE in write.csv to avoid extra row numbers in the file.

CSV files are simple text files, so you can open them with any text editor or spreadsheet program.

Summary

read.csv loads CSV files into R as data frames.

write.csv saves data frames from R into CSV files.

These functions help you move data between R and other tools easily.