CSV Files
Data within CSV files can be read and written to using the read.csv()
and write.csv()
functions.
Reading Data
The read.csv()
function reads data from a CSV file.
Syntax
read.csv(file)
A file
with a .csv
extension is read from the read.csv()
function.
Example
Suppose there is a students.csv
file with the following data in it:
First Name | Last Name | Grade | ID |
---|---|---|---|
Rita | Aros | 3 | N76654 |
Noah | Chen | 1 | N75435 |
Averill | Freeman | 9 | N43542 |
Stephen | Holmes | 11 | N97543 |
Blake | Jones | 12 | N85342 |
Francesca | Mahone | 8 | N49854 |
Katelyn | Miller | 2 | N58632 |
Martin | Phillman | 5 | N86873 |
Carl | Sanchez | 4 | N43263 |
April | Tillman | 7 | N63430 |
Tori | Vega | 10 | N76543 |
Frank | Williams | 3 | N86532 |
Robert | Ye | 10 | N67541 |
The data can be retrieved using the read.csv()
function and then printed:
# Reading csv filesdata <- read.csv("students.csv")# Print out informationprint(data)
This reads the data in as a data frame. The output would be the following:
First.Name Last.Name Grade ID1 Rita Aros 3 N766542 Noah Chen 1 N754353 Averill Freeman 9 N435424 Stephen Holmes 11 N975435 Blake Jones 12 N853426 Francesca Mahone 8 N498547 Katelyn Miller 2 N586328 Martin Phillman 5 N868739 Carl Sanchez 4 N4326310 April Tillman 7 N6343011 Tori Vega 10 N7654312 Frank Williams 3 N8653213 Robert Ye 10 N67541
Writing Files
The write.csv()
function can be used to write data into CSV files.
Syntax
write.csv(data, file)
data
: The information to write into the.csv
file.file
: Name of the file with a.csv
extension to write thedata
into.
Example
The following example uses the subset()
function to retrieve students that are above grade 8
from the students.csv
file. Then it writes the subset into the highSchoolers.csv
file using the write.csv()
function:
# Retrieve data from CSV filedata <- read.csv("students.csv")# Get subset of students in grades higher than 8higherGrades <- subset(data, Grade > 8)# Write the subset into a new CSV filewrite.csv(higherGrades, "highSchoolers.csv")
The example above will return the highSchoolers.csv
file with the following data in it:
First.Name Last.Name Grade ID3 Averill Freeman 9 N435424 Stephen Holmes 11 N975435 Blake Jones 12 N8534211 Tori Vega 10 N7654313 Robert Ye 10 N67541
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn R on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn R
Learn how to code and clean and manipulate data for analysis and visualization with the R programming language.Beginner Friendly14 hours