Here are three ways to import CSV files into R:
- Using the read.csv() function from base R
- Using the read_csv() function from the readr package
- Using the fread() function from data.table package
Method 1: Using the read.csv() function from base R
The read_csv() function comes with base R, so no additional libraries are needed, and it is easy to use.
Syntax
data <- read.csv("file_path.csv")
Example
Let’s say we are working with mlb_players.csv data.
# Load the readxl package
library(readxl)
# Read an Excel file into a data frame
my_data <- read.csv("mlb_players.csv")
# Display the first few rows of the data
head(my_data)
Output
Method 2: Using read_csv() from the readr package
The read_csv() function from the readr package is Faster than the read.csv() function. It provides more options for specifying data types, date formats, etc. As a part of the tidyverse, it integrates well with other tidyverse packages like dplyr, ggplot2, etc.
Syntax
library(readr)
data <- read_csv("file_path.csv")
Example
# Load the readxl package
library(readr)
# Read an Excel file into a data frame
my_data <- read_csv("mlb_players.csv")
# Display the first few rows of the data
head(my_data)
Output
Method 3: Using fread() from the data.table package
The fread() function from the data.table package is used in extremely large datasets. It can read data in chunks. Automatically detects separators, headers, data types, etc.
Syntax
library(data.table)
data <- fread("file_path.csv")
Example
# Load the readxl package
library(data.table)
# Read an Excel file into a data frame
my_data <- fread("mlb_players.csv")
# Display the first few rows of the data
head(my_data)
Output
When to use which method and why
-
Base R’s read.csv():
- When to Use: Ideal for beginners or quick, ad-hoc tasks where you don’t need to load additional libraries.
- Why: Easy to use, no need for additional libraries.
- readr’s read_csv():
- When to Use: When working within the tidyverse ecosystem and needing more speed and flexibility than base R.
- Why: Faster, more flexible, and integrates well with other tidyverse packages.
-
data.table’s fread():
- When to Use: When you have huge datasets and need the fastest reading times, or you already use
data.table
for its other features. - Why: Extremely fast, especially for large datasets, and provides advanced capabilities like chunk reading.
- When to Use: When you have huge datasets and need the fastest reading times, or you already use
That’s it!
Related posts
Read CSV File into DataFrame in R

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.