Fisseha Berhane, PhD

Data Scientist

443-970-2353 fisseha@jhu.edu 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 [ ]:
my_packages=c("manipulate","dbscan","tm","downloader","wordcloud","rgdal","httr","rvest","ggmap","calibrate","maps","maptools","stringi","caret","nnet","NeuralNetTools","tidyr","ggthemes","gridExtra","shiny","shinydashboard","plyr","RCurl","ROAuth","twitteR","chron","RColorBrewer","lattice","lubridate","sp","fields","ROCR","caTools","rpart","e1071","randomForest","plotmo","XML","xlsx","readr","scales","reshape2","gtrendsR")
  • The function installed.packages gives a matrix of all the instaled packages with their attributes.
  • I am setting the mirror to "http://cran.us.r-project.org" 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='http://cran.us.r-project.org',dependencies = TRUE)
                     }
        lapply(packages,library, character.only = TRUE)
  }
Then, just use the function above
In [ ]:
install_load(my_packages)
comments powered by Disqus