Fisseha Berhane, PhD

Data Scientist

443-970-2353 [email protected] CV Resume Linkedin GitHub twitter twitter

Installing and loading many R packages at once

I like Jupyter notebook because it enables me to use R, Python and Matlab on the same session. Recently, I was trying to insall other kernels and for unknown reason my Jupyter notebook crushed. Then, I uninstalled Anaconda and reinstalled it. The problem, I lost all R packages I installed over time. Then, I wanted to check if I can install and load the packages I want using a function. This short post shows how to achieve that.

The function below enabled me to check if the packages are installed and then load them. If they are not installed, it will install them first.

Packages I want to install

In [ ]:
  • The function installed.packages gives a matrix of all the instaled packages with their attributes.
  • I am setting the mirror to "" but other mirrors can also be used.
  • Even if installing many packages of interest at once is useful, it is known that we probably will not use all of them in one session. We can modify the function below for only installing packages or use it as it is if we are including only packages that we want to use in the session we are working on.

A function that performs the required task

In [ ]:
install_load= function(packages){
   to_install <- packages[!(packages %in% installed.packages()[, "Package"])]
    if (length(to_install)){
        install.packages(to_install, repos='',dependencies = TRUE)
        lapply(packages,library, character.only = TRUE)
Then, just use the function above
In [ ]:
comments powered by Disqus