What is the difference between require()
and library()
?
?library
and you will see:
library(package)
andrequire(package)
both load the package with namepackage
and put it on the search list.require
is designed for use inside other functions; it returnsFALSE
and gives a warning (rather than an error aslibrary()
does by default) if the package does not exist. Both functions check and update the list of currently loaded packages and do not reload a package which is already loaded. (If you want to reload such a package, calldetach(unload = TRUE)
orunloadNamespace
first.) If you want to load a package without putting it on the search list, userequireNamespace
.
My initial theory about the difference was that library
loads the packages whether it is already loaded or not, i.e. it might reload an already loaded package, while require
just checks that it is loaded, or loads it if it isn't (thus the use in functions that rely on a certain package). The documentation refutes this, however, and explicitly states that neither function will reload an already loaded package.
library
. Never use require
.In a nutshell, this is because, when using require
, your code might yield different, erroneous results, without signalling an error. This is rare but not hypothetical! Consider this code, which yields different results depending on whether {dplyr} can be loaded:
require(dplyr)
x = data.frame(y = seq(100))
y = 1
filter(x, y == 1)
This can lead to subtly wrong results. Using library
instead of require
throws an error here, signalling clearly that something is wrong. This is good.
It also makes debugging all other failures more difficult: If you require
a package at the start of your script and use its exports in line 500, you’ll get an error message “object ‘foo’ not found” in line 500, rather than an error “there is no package called ‘bla’”.
The only acceptable use case of require
is when its return value is immediately checked, as some of the other answers show. This is a fairly common pattern but even in these cases it is better (and recommended, see below) to instead separate the existence check and the loading of the package. That is: use requireNamespace
instead of require
in these cases.
More technically, require
actually calls library
internally (if the package wasn’t already attached — require
thus performs a redundant check, because library
also checks whether the package was already loaded). Here’s a simplified implementation of require
to illustrate what it does:
require = function (package) {
already_attached = paste('package:', package) %in% search()
if (already_attached) return(TRUE)
maybe_error = try(library(package, character.only = TRUE))
success = ! inherits(maybe_error, 'try-error')
if (! success) cat("Failed")
success
}
Yihui Xie, author of {knitr}, {bookdown} and many other packages says:
Ladies and gentlemen, I've said this before: require() is the wrong way to load an R package; use library() instead
Hadley Wickham, author of more popular R packages than anybody else, says
Use
library(x)
in data analysis scripts. […] You never need to userequire()
(requireNamespace()
is almost always better)
You can use require()
if you want to install packages if and only if necessary, such as:
if (!require(package, character.only=T, quietly=T)) {
install.packages(package)
library(package, character.only=T)
}
For multiple packages you can use
for (package in c('<package1>', '<package2>')) {
if (!require(package, character.only=T, quietly=T)) {
install.packages(package)
library(package, character.only=T)
}
}
Pro tips:
When used inside the script, you can avoid a dialog screen by specifying the repos
parameter of install.packages()
, such as
install.packages(package, repos="http://cran.us.r-project.org")
You can wrap require()
and library()
in suppressPackageStartupMessages()
to, well, suppress package startup messages, and also use the parameters require(..., quietly=T, warn.conflicts=F)
if needed to keep the installs quiet.
In addition to the good advice already given, I would add this:
It is probably best to avoid using require()
unless you actually will be using the value it returns e.g in some error checking loop such as given by thierry.
In most other cases it is better to use library()
, because this will give an error message at package loading time if the package is not available. require()
will just fail without an error if the package is not there. This is the best time to find out if the package needs to be installed (or perhaps doesn't even exist because it it spelled wrong). Getting error feedback early and at the relevant time will avoid possible headaches with tracking down why later code fails when it attempts to use library routines
Here seems to be the difference on an already loaded package. While it is true that both require and library do not load the package. Library does a lot of other things before it checks and exits.
I would recommend removing "require" from the beginning of a function running 2mil times anyway, but if, for some reason I needed to keep it. require is technically a faster check.
microbenchmark(req = require(microbenchmark), lib = library(microbenchmark),times = 100000)
Unit: microseconds
expr min lq mean median uq max neval
req 3.676 5.181 6.596968 5.655 6.177 9456.006 1e+05
lib 17.192 19.887 27.302907 20.852 22.490 255665.881 1e+05