Before submitting a project or setting up R on a new system, this function might come in handy. You can put all your favourite or required packages into a single vector and check if they’re already installed.
If not, packageChecker() will take care of that.
copyable snippet
packageChecker <- function(requiredPacks){ check <- requiredPacks %in% installed.packages()[,”Package”] for(i in 1:length(check)){ if(check[i] == FALSE){ install.packages(requiredPacks[i]) } } } # execution requiredPacks <- c(“pwltools”, “sp”, “raster”, “ggplot2”, “RStoolbox”) packageChecker(requiredPacks)
Edit:
Once I completed coding this, I realized that installing the packages might only be half the job. You’ll most likely want to load them into your R session before executing the rest of your code.
While researching how to operate vectors on library() I found a neat existing solution.
But adding this inside the loop will do the trick.
copyable snippet
sapply(requiredPacks, require, character.only = TRUE)
Thanks to Steven Worthington.