Author

Gary Hutson

Published

August 17, 2018

Modified

March 23, 2024

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")

install_or_load_pack(packages)

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:


   ggplot2     plotly data.table  tidyverse      caret 
      TRUE       TRUE       TRUE       TRUE       TRUE 

This blog was written by Gary Hutson, Principal Analyst, Activity & Access Team, Information & Insight at Nottingham University Hospitals NHS Trust, and was originally posted on Hutson Hacks.

Back to top

Reuse

CC0

Citation

For attribution, please cite this work as:
Hutson, Gary. 2018. “A Simple Function to Install and Load Packages in R.” August 17, 2018. https://nhs-r-community.github.io/nhs-r-community//blog/a-simple-function-to-install-and-load-packages-in-r.html.