6.2 C
London
Thursday, December 19, 2024
HomeRImport & Export Data in RHow to Read a CSV from a URL in R (3 Methods)

How to Read a CSV from a URL in R (3 Methods)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

There are three methods you can use to read a CSV file from a URL in R:

Method 1: Use Base R

data csv('https://website.com/data.csv')

Method 2: Use data.table Package

library(data.table)

data 

Method 3: Use readr Package

library(readr)

data 

Each method works the same, but the data.table and readr methods tend to be much quicker if you’re reading a large dataset.

The following examples show how to use each method in practice.

Method 1: Use Base R

The following code shows how to import a CSV file from a URL using Base R:

#import data from URL
data csv('https://raw.githubusercontent.com/Statology/Miscellaneous/main/basketball_data.csv')

#view first five rows
head(data)

  player assists points
1      A       6     12
2      B       7     19
3      C      14      7
4      D       4      6
5      E       5     10

#view class of data
class(data)

[1] "data.frame"

Method 2: Use data.table

The following code shows how to import a CSV file from a URL using the data.table package:

library(data.table)

#import data from URL
data2 #view first five rows
head(data2)

   player assists points
1:      A       6     12
2:      B       7     19
3:      C      14      7
4:      D       4      6
5:      E       5     10

#view class of data
class(data2)

[1] "data.table" "data.frame"

Method 3: Use readr

The following code shows how to import a CSV file from a URL using the readr package:

library(readr)

#import data from URL
data3 #view first five rows
head(data3)

  player assists points
        
1 A            6     12
2 B            7     19
3 C           14      7
4 D            4      6
5 E            5     10

#view class of data
class(data3)

[1] "spec_tbl_df" "tbl_df"      "tbl"         "data.frame" 

Additional Resources

The following tutorials explain how to import other types of files into R:

How to Import CSV Files into R
How to Import Excel Files into R
How to Import SPSS Files into R
How to Import SAS Files into R
How to Import Stata Files into R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories