Chapter 10 Useful Code Snippets & Tricks
This section includes helpful code snippets, shortcuts, tips, and tricks that will make your coding life a little bit easier.
10.1 R Package Installer
It can be annoying to install package by package when you first setting up your environment. Here is the function that I created that installs and loads a bunch of initial packages for you.
#install procedures for relevant R packages---------------------------------------------------------------------
#author: Nikita Voevedin
#notes: this script is revisited for updates every month, note that you may have to install a package seperately
#COPY THIS SCRIPT AND RUN IN RSTUDIO
#######################script that automatically installs all libraries in a vector##############################
<- function(x){
installer for( i in x ){
if( !require( i , character.only = TRUE ) ){
# If not loading - install
install.packages( i , dependencies = TRUE )
# Load
require(i, character.only = TRUE )
}
}
}
#########################################################################################################################
installer( c("ggplot2" , "reshape2" , "data.table", 'shiny', 'shinydashboard', 'fasttime', 'lubridate',
'dplyr', 'httr', 'jsonlite', 'RCurl', 'pbapply', 'tidyverse', 'openxlsx', 'readxl',
'reshape', 'tidyr', 'plyr', 'ggmap', 'leaflet', 'raster', 'sf', 'rgdal', 'leaflet.extras',
'remotes', 'stringi', 'shiny', 'rgeos', 'rmapshaper', 'sp', 'echarts4r', 'shinydashboardPlus',
'shinycssloaders', 'DT', 'mapview','parallel') )
###########################################################################################################################
10.2 FST data format
Although it is ok to use csv and for 90% of our tasks we will be using csvs, if the amount of data is too big and you need faster loading speeds, you can use fst files. Fst files leverage SSD drive speeds and were created by data teams at facebook to speed up read and write times. Since they are native to R, they are easier to read in R. Make sure you have the fst packge installed with the install.packages(“fst”). Below you can see how you read in a file:
library(fst)
library(data.table)
#working directory
setwd("I:/COF/COF/_M3trics2/records/med")
#Extracting one day of medallion data
<- read.fst(list.files(pattern = "2017-01-01"), as.data.table = T) data
This work is licensed under a Creative Commons Attribution 4.0 International License.