Skip to content
Prev 269012 / 398506 Next

Using require() vs. library()

On 8/17/2011 11:13 AM, Uwe Ligges wrote:
I think the unstated corollary is that library() is preferred when not 
inside a function, but within a file that might be sourced.  That is 
because if the package can not be loaded, execution will halt at that 
point.  If require were used, then execution would continue, almost 
certainly unsuccessfully.  Compare two files:

library("nonexistant")
print("done")

versus

require("nonexistant")
print("done")

Sourcing the first gives:

Error in library("nonexistant") :
   there is no package called 'nonexistant'

Sourcing the second gives:

Loading required package: nonexistant
[1] "done"
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, 
logical.return = TRUE,  :
   there is no package called 'nonexistant'

Maybe put another way, if you aren't going to do anything with the 
return value of require, then you are probably better off using library 
so it fails sooner.