Reading CSV Files
in R
Learn to import comma-separated data into R using read.csv() and readr::read_csv(): the essential first step in any data analysis workflow.
What Is a CSV File?
A CSV (Comma-Separated Values) file is a plain text file where each line represents a row of data and each value within that row is separated by a comma. It is the most common format for sharing tabular data.
Why CSV Matters
Anatomy of a CSV File
The Core Function: read.csv()
read.csv() is built into base R: no packages needed. It reads a CSV file and returns a data.frame.
The Modern Alternative: read_csv()
readr::read_csv() from the tidyverse is faster, gives cleaner output, and returns a tibble instead of a data.frame.
read.csv() vs. read_csv()
| read.csv() | read_csv() | |
|---|---|---|
| Package | Base R (built-in) | readr (tidyverse) |
| Returns | data.frame | tibble |
| Speed | Slower on large files | Faster (C++ engine) |
| Strings | Factor (\( R < 4.0 \)) | Always character |
| Column specs | None shown | Prints summary |
| Encoding | System default | UTF-8 always |
Key Parameters You Should Know
How to Read a CSV Step by Step
Example 1: Basic CSV Read
Example 2: Custom Parameters
Suppose your CSV uses semicolons as delimiters, has 2 metadata lines at the top, and uses "N/A" for missing values.
Example 3: Using readr::read_csv()
Reading from a URL
Both functions accept a URL instead of a local file path. R will download the file automatically.
Inspecting Your Data
After reading a CSV, always inspect the result to confirm it loaded correctly.
Common Mistakes
Question 1 of 5
Which function is built into base R and requires no additional packages to read a CSV file?
Question 2 of 5
What type of object does readr::read_csv() return by default?
Question 3 of 5
Your CSV file has 3 lines of metadata at the top before the actual data starts. Which parameter lets you skip those lines?
Question 4 of 5
You run read.csv("data.csv") and the resulting data frame has only 1 column with values like "Alice;16;A". What is the most likely problem?
Question 5 of 5
After loading a CSV, which R function gives you a quick look at the first 6 rows of your data?