A simple function to install and load packages in R

One function to rule the world, or install or load your packages for you

I was starting to despair at the amount of packages I end up using during the task of transforming, cleaning, modelling and validating some of my models. I thought there must be a simple approach to dealing with this?

So, I started to ponder if I could create a function that would just install and then load the packages straight into R in one go. I found the solution and it can be applied to all your projects – all you have to do is supply the list of packages to the function and “hey presto!”

Run the below function and I will explain what this does:

install_or_load_pack <- function(pack){
  create.pkg <- pack[!(pack %in% installed.packages()[, "Package"])]
  if (length(create.pkg))
    install.packages(create.pkg, dependencies = TRUE)
  sapply(pack, require, character.only = TRUE)
#I know I should be using purr here, but this is before the Tidyverse is loaded. I know you Tidyverse trend setters will have me here.

This creates a function, in which, you can pass a vector of packages you want to load. The sweet point with this function is that if the packages are not installed, this function will do that and then load them, so the next time you come to using the function it will just load them into your project – instead of installing them. I said it was cool, or I thought you might find it cooler than I expected, either way I still think it’s cool.

The last step is to make a call to the function and specify the list of packages you need:

packages <- c("ggplot2", "plotly",  "data.table", "tidyverse", "caret")

If the packages are not installed then this will show an installation series in the console window, otherwise it will just flag a Boolean value to show that they are now active in the project:

There you go – this will save you some time and will mean that you don’t have to go library(ggplot2), then library(plotly), etc. Use wisely!

This post appears on R-Bloggers – please check out all the other cool blogs featured on this site.
2 comments Add yours

Leave a Reply