How to Import CSV Files into R [4 Ways]

Here are four ways to import CSV files into R:

  1. Using read.csv() function from base R
  2. Using RStudio GUI
  3. Using read_csv() function from the readr package
  4. Using fread() function from data.table package

Let’s say we are working with mlb_players.csv data. The screenshot of the data is this:

Screenshot of dataset

Method 1: Using the read.csv() function

Syntax

data <- read.csv("file_path.csv")

Example

# 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

Using the read.csv() function from base R

Method 2: Using RStudio GUI

Step 1: Open RStudio

Screenshot of RStudio

Step 2: Go to Import Dataset

Go to File -> Import Dataset and select From Text (readr) option.

Go to ‘Import Dataset’ in RStudio

Step 3:  Browsing CSV File

 Select your CSV file

Step 4: Selecting CSV File

Selecting CSV File

Step 5: Click on ‘Import’

Click import button of Visual Studio Code

Step 6: Viewing CSV data on RStudio

Viewing CSV Data in RStudio

Method 3: 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

Using read_csv() from the readr package

Method 4: 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

Using fread() from the data.table package

That’s it!

    Related posts

    Import Excel Files

    Export DataFrame to CSV

    Read CSV File into DataFrame

    Leave a Comment