A simple function to install and load packages in R

[This article was first published on R Blogs – Hutsons-hacks, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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

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.

To leave a comment for the author, please follow the link and comment on their blog: R Blogs – Hutsons-hacks.

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.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)