Table of Contents
In R, there are three main methods for reading a CSV from a URL: using the read.csv function, using the RCurl package, and using the curl package. The read.csv function is the simplest approach, while the RCurl and curl packages offer more advanced options and are useful for more complex data sets. All three methods allow you to quickly and easily read a CSV from a URL directly into R.
There are three methods you can use to read a CSV file from a URL in R:
Method 1: Use Base R
data <- read.csv('https://website.com/data.csv')
Method 2: Use data.table Package
library(data.table)
data <- fread('https://website.com/data.csv')
Method 3: Use readr Package
library(readr)
data <- read_csv('https://website.com/data.csv')
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 <- read.csv('https://raw.githubusercontent.com/arabpsychology/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 package:
library(data.table) #import data from URL data2 <- fread('https://raw.githubusercontent.com/arabpsychology/Miscellaneous/main/basketball_data.csv') #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 package:
library(readr) #import data from URL data3 <- fread('https://raw.githubusercontent.com/arabpsychology/Miscellaneous/main/basketball_data.csv') #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"
The following tutorials explain how to import other types of files into R: