DIFFERENCE BETWEEN library() AND require() IN R

[This article was first published on R – Greetz to Geeks, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

The library() and require() can be used to attach and load add-on packages which are already installed. The installed packages are identified with the help of the ‘DESCRPTION’ file which contains Build:field. The name of the package which need to be loaded using the library() and require() must match the name of the package’s ‘DESCRPTION’ file.

Note: The package names are case sensitive.

Both these functions keep updating the list of the attached packages without reloading the namespaces which are already loaded.

The main difference between these functions are,

The library() by default returns an error if the requested package does not exist.

example:
> library(xyz)
Error in library(xyz) : there is no package called ‘xyz’

The require() is designed to be used inside functions as it gives a warning message and returns a logical value say, FALSE if the requested package is not found and TRUE if the package is loaded.

example:
> require(xyz)
Loading required package: xyz
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, :
there is no package called ‘xyz’

It is better to use the library() as it gives the error message if the package is not found during the package loading time. This will indeed avoid unnecessary headaches of tracking down the errors caused while attempting to use the library routines which are not installed.


To leave a comment for the author, please follow the link and comment on their blog: R – Greetz to Geeks.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)