Fast data loading from files to R
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Recently we were building a Shiny App in which we had to load data from a very large dataframe. It was directly impacting the app initialization time, so we had to look into different ways of reading data from files to R (in our case customer provided csv files) and identify the best one.
The goal of my post is to compare:
read.csv
fromutils
, which was the standard way of reading csv files to R in RStudio,read_csv
fromreadr
which replaced the former method as a standard way of doing it in RStudio,load
andreadRDS
frombase
, andread_feather
fromfeather
andfread
fromdata.table
.
Data
First let’s generate some random data
and save the files on a disk to evaluate the loading time. Besides the csv
format we will also need feather
, RDS
and Rdata
files.
Next let’s check our files sizes:
As we can see both csv
and feather
format files are taking much more storage space. Csv
more than 6 times and feather
more than 4 times comparing to RDS
and RData
.
Benchmark
We will use microbenchmark
library to compare the reading times of the following methods:
- utils::read.csv
- readr::read_csv
- data.table::fread
- base::load
- base::readRDS
- feather::read_feather
in 10 rounds.
And the winner is… feather
! However, using feather
requires prior conversion of the file to the feather format.
Using load
or readRDS
can improve performance (second and third place in terms of speed) and has a benefit of storing smaller/compressed file. In both cases you will have to convert your file to the proper format first.
When it comes to reading from csv
format fread
significantly beats read_csv
and read.csv
, and thus is the best option to read a csv
file.
In our case we decided to go with feather
file since conversion from csv
to this format is just a one time job and we didn’t have a strict limitation on a storage space to consider usage of Rds
or RData
format.
The final workflow was:
- reading a
csv
file provided by our customer usingfread
, - writing it to
feather
usingwrite_feather
, and - loading a
feather
file on app initialization usingread_feather
.
First two tasks were done once and outside of a Shiny App context.
There is also quite interesting benchmark done by Hadley here on reading complete files to R. Unfortunately, if you use functions defined in that post, you will end up with an character type object, and you will have to apply string manipulations to obtain a commonly and widely used dataframe.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.