DIFFERENCE BETWEEN library() AND require() IN R

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s