R Read and Write CSV Files
CSV Files
So far, you have typed the data into your code. But real data usually comes from a file.
A very common file type for data is CSV (Comma-Separated Values). A CSV file is a plain text file, where each line is a row, and the values are separated by commas. You can save a CSV file from programs like Excel and Google Sheets.
This is how a CSV file with three people looks inside:
people.csv
Name,Age
John,30
Liam,25
Jenny,35
The first line holds the column names.
Write a CSV File
Use the write.csv() function to save a data frame as a CSV file. If you leave out the file name, R shows the CSV text on the screen, so you can see what the file will look like:
Example
Data_Frame <- data.frame (
Name = c("John", "Liam", "Jenny"),
Age = c(30, 25, 35)
)
write.csv(Data_Frame, row.names = FALSE)
Try it Yourself »
To save it in a file, add the file name as the second argument:
Example
Data_Frame <- data.frame (
Name = c("John", "Liam", "Jenny"),
Age = c(30, 25, 35)
)
write.csv(Data_Frame, "people.csv", row.names = FALSE)
file.exists("people.csv")
Try it Yourself »
The row.names = FALSE argument tells R not to save the row numbers (1, 2, 3) as an extra column.
Read a CSV File
Use the read.csv() function to read a CSV file into a data frame:
Example
Data_Frame <- data.frame (
Name = c("John", "Liam", "Jenny"),
Age = c(30, 25, 35)
)
write.csv(Data_Frame, "people.csv", row.names = FALSE)
people <- read.csv("people.csv")
people
Try it Yourself »
In our example, we first create the file with write.csv(), so that there is a file to read. On your own computer, you just read the file you already have.
Note: If the file is in another folder, write the whole path, with forward slashes, for example read.csv("C:/data/people.csv").
Work with the Data
When the data is in a data frame, you can use everything you have learned, like nrow() and mean():
Example
Data_Frame <- data.frame (
Name = c("John", "Liam", "Jenny"),
Age = c(30, 25, 35)
)
write.csv(Data_Frame, "people.csv", row.names = FALSE)
people <- read.csv("people.csv")
nrow(people)
mean(people$Age)
Try it Yourself »
Read CSV Text
You can also give read.csv() the CSV text directly with the text argument. This is handy when you want to test something quickly:
Example
people <- read.csv(text = "Name,Age
John,30
Liam,25
Jenny,35")
people
Try it Yourself »