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