There are several ways of loading a package, two of these ways are library()
and require()
functions. Both of these function load the functions that are in the requested library but they return two separate things.
The library()
function actually returns all the libraries currently loaded when you call it
libs = library(dplyr)
print(libs)
[1] "dplyr" "knitr" "rmarkdown" "stats"
[5] "graphics" "grDevices" "utils" "datasets"
[9] "base"
The require()
function returns whether or not the library was able to be loaded, which if it fails is normally due to the fact that it doesn’t exist
libLoaded = require(dplyr)
print(libLoaded)
[1] TRUE
That means you can take advantage of the return of require()
to ensure a packaged is installed without having to call install.packages()
every time you want a package.
if(!require(dplyr)){
install.packages("dplyr")
#call require again because install.packages simply installs the package, it doesn't load it
require(dplyr)
}
If you put the above code at the top of your script it will only call install.package
if it has to. You can also turn the above into a function to be reused.
ensureLib <-function(libName){
if(!require(libName, character.only = T)){
install.packages(libName)
#call require again because install.packages simply installs the package, it doesn't load it
require(libName, character.only = T)
}
}
ensureLib("dplyr")