Contact Us

Use the form on the right to contact us.

You can edit the text in this area, and change where the contact form on the right submits to, by entering edit mode using the modes on the bottom right. 

#4200-6270 University Blvd.
Vancouver, BC

Functional morphologist and evolutionary biologist


A Hassle-Free Way to Verify that R Packages are Installed and Loaded

Vikram Baliga

2019-04-28: Please note, this entry also appears on my new blog - see here.

Say you have an R script shared between you and several colleagues. You may not be sure that each user with whom you're collaborating has installed all the packages the script will require. Using install.packages() would be unnessary for users who already have the packages and simply need to load them.

The code below provides an easy way to check whether specific packages are in the default Library. If they are, they're simply loaded. If any packages are missing, they're installed (with dependencies) into the default Library and are then loaded.

The code provides an example using 4 packages (all of which are very commonly used in macroevolutionary analyses), but the list could be adjusted to specify as many as needed. For verifying the installation of & loading very few packages, this code may not be that efficient. But if the user will be employing code from a large number of packages (say 10+), using the package.check() function here becomes a lifesaver.

#specify the packages of interest
packages = c("ape","MASS","phytools","geomorph")

#use this function to check if each package is on the local machine
#if a package is installed, it will be loaded
#if any are not, the missing package(s) will be installed and loaded
package.check <- lapply(packages, FUN = function(x) {
    if (!require(x, character.only = TRUE)) {
        install.packages(x, dependencies = TRUE)
        library(x, character.only = TRUE)

#verify they are loaded

The above code is also available here as a .R script file.

Feel free to comment, especially if you think the code could be streamlined/improved.