Loading large dataframes when building Shiny Apps can have a significant impact on the app initialization time. When we ran into this issue in a recent project, we decided to conduct a review of the available methods for reading data from csv files (as provided by our client) to R. In this article we will identify the most efficient of these methods using benchmarking and explain our workflow.
We will compare the following:
utils, which was the standard way of reading csv files to R in RStudio,
readrwhich replaced the former method as a standard way of doing it in RStudio,
We need to generate some random data to commence with our test…
…and save the files on a disk to evaluate the load time. Besides the
csv format we will also need
Next, we can check the resulting file sizes:
feather format files take up much more storage space.
Csv takes up 6 times and
feather 4 times more space as compared to
Looking to learn more about importing data into R, this DataCamp tutorial covers all you need to know about importing simple text files to more advanced SPSS and SAS files.
We will use the
microbenchmark library to compare the read times in 10 rounds for the following methods:
And the winner is…
feather! However, using
feather requires prior conversion of the file to the feather format.
readRDS can improve performance (second and third place in terms of speed) and has an added benefit of storing a smaller/compressed file. In both cases it is necessary to first convert the file to the proper format.
When it comes to reading from the
fread significantly beats
read.csv, and thus is the best option to read a
Ultimately, we chose to work with
feather files. The
feather conversion process is quick and we did not have a strict limitation on storage space in which case either the
RData formats could probably have been a more appropriate choice.
The final workflow was:
csvfile provided by our customer using
featherfile on app initialization using
The first two tasks were done once and outside of the Shiny App context.
There is also quite an interesting benchmark done by Hadley here on reading complete files to R. Please note that if you use functions defined in that post, you will end up with a character type object and will have to apply string manipulations to obtain a commonly and widely used dataframe.
If you run into any issues, as an RStudio Full Certified Partner, our team at Appsilon is ready to answer your questions about loading data into R and other topics related to R Shiny, Data Analytics, and Machine Learning. We’re experts in this area, and we’d love to chat with you.