How to Read a CSV File in R
Learn how to import CSV files into R using read.csv() and the tidyverse readr package.
Importing CSV files is a fundamental skill in R for data analysis. Here are the main approaches.
Method 1: Using read.csv() (Base R)
The simplest way to read a CSV file:
# Read a CSV file
df <- read.csv("data.csv")
# View the first few rows
head(df)
Common Options
# Specify that strings should not be converted to factors
df <- read.csv("data.csv", stringsAsFactors = FALSE)
# Skip rows
df <- read.csv("data.csv", skip = 2)
# No header row
df <- read.csv("data.csv", header = FALSE)
# Handle different delimiters
df <- read.csv2("data.csv") # For semicolon-separated files
Method 2: Using readr (Tidyverse)
The readr package offers faster and more consistent CSV reading:
library(readr)
# Read a CSV file
df <- read_csv("data.csv")
# View the data
print(df)
Advantages of readr
# Automatically parses column types
# Shows a column specification
# Faster for large files
# Returns a tibble instead of data.frame
df <- read_csv("data.csv",
col_types = cols(
name = col_character(),
age = col_integer()
))
Method 3: Using data.table
For very large files, data.table is extremely fast:
library(data.table)
df <- fread("data.csv")
Summary
- Use
read.csv()for quick, simple imports - Use
read_csv()from readr for tidyverse workflows - Use
fread()from data.table for large files