DIFFERENCE BETWEEN library() AND require() IN R

December 8, 2016
By

(This article was first published on R – Greetz to Geeks, and kindly contributed to R-bloggers)

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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Sponsors

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)