Function to check R package installation status

30. August 2016 how to, r 0
Function to check R package installation status

Today, I was updating a script that a coworker might use while I’m on vacation.  Knowing that she might not have some of the necessary packages installed on her machine, I wrote a function to check if the package was installed.  If the package is missing, the function will install it; if a package is already installed, the message “[PackageName] is already installed” is printed to the console.

The is.installed() function I wrote uses the is.element() function to call the installed.packages() function. [mouthful, I know]

installed.packages() returns a data frame of installed package information, but we only look at the first column in the output, which is the name of the installed packages.

needed = c("lubridate", "dplyr", "data.table", "stringr")

is.installed <- function(pkg){
  is.element(pkg, installed.packages()[,1])

# For loop to run through each of the packages
for (p in 1:length(needed)){
  ifelse(!is.installed(needed[p]), install.packages(needed[p]), print(paste(needed[p], " is already installed", sep = "")))

Leave a Reply