What is the difference between require() and library()? What is the difference between require() and library()? r r

What is the difference between require() and library()?


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'> testError: object 'test' not found> test <- require("abc")Loading required package: abcWarning 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")    }}


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