What is the difference between require()
and library()
?
As explained in Example 1, the major difference between library and require is that library returns an error and require returns a warning in case a package is not installed yet. This is especially relevant when we want to use packages within user-defined functions.
In R, a package is a collection of R functions, data and compiled code. The location where the packages are stored is called the library. If there is a particular functionality that you require, you can download the package from the appropriate site and it will be stored in your library.
A library is a set of modules which makes sense to be together and that can be used in a program or another library. A package is a unit of distribution that can contain a library or an executable or both. It's a way to share your code with the community.
There's not much of one in everyday work.
However, according to the documentation for both functions (accessed by putting a ?
before the function name and hitting enter), require
is used inside functions, as it outputs a warning and continues if the package is not found, whereas library
will throw an error.
Another benefit of require()
is that it returns a logical value by default. TRUE
if the packages is loaded, FALSE
if it isn't.
> test <- library("abc") Error in library("abc") : there is no package called 'abc' > test Error: object 'test' not found > test <- require("abc") Loading required package: abc Warning message: In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, : there is no package called 'abc' > test [1] FALSE
So you can use require()
in constructions like the one below. Which mainly handy if you want to distribute your code to our R installation were packages might not be installed.
if(require("lme4")){ print("lme4 is loaded correctly") } else { print("trying to install lme4") install.packages("lme4") if(require(lme4)){ print("lme4 installed and loaded") } else { stop("could not install lme4") } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With