Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

package

r

r-faq

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

like image 801
Marco Avatar asked Apr 08 '11 13:04

Marco


People also ask

What is the difference between require and library?

As explained in Example 1, the major difference between library and require is that library returns an error and require returns a warning in case a package is not installed yet. This is especially relevant when we want to use packages within user-defined functions.

What is the difference between library and package in R?

In R, a package is a collection of R functions, data and compiled code. The location where the packages are stored is called the library. If there is a particular functionality that you require, you can download the package from the appropriate site and it will be stored in your library.

What is a package library?

A library is a set of modules which makes sense to be together and that can be used in a program or another library. A package is a unit of distribution that can contain a library or an executable or both. It's a way to share your code with the community.


2 Answers

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.

like image 82
richiemorrisroe Avatar answered Oct 23 '22 02:10

richiemorrisroe


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' > test Error: object 'test' not found > test <- require("abc") Loading required package: abc Warning 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")     } } 
like image 38
Thierry Avatar answered Oct 23 '22 02:10

Thierry