Open In App

The Difference Between require() and library() in R

Last Updated : 01 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

R Programming Language has a lot of packages with different functions which can be used for data analysis. To make use of the functions, we have to install the packages to which the functions belong.

Difference Between require() and library() in R

require()

library()

Only gives a warning if the package is not available.

Gives an error if the package is not available.

The rest of the script will be executed even if the package is not available.

Execution stops when an error occurs.

Mostly used inside functions to check the availability of a package before using its functionality.

Mostly used at the beginning of the script to load required packages that have been installed beforehand.

Installing packages in R

We write “install.packages()” to install new packages. For example, this is how we would install the “tidyr” package

install.packages("tidyr")

Loading packages in R

Once the packages have been installed, we need to load them in the current environment. Packages can be loaded in R using two methods.

  1. library()
  2. require()

Load package using library()

The mlbench or the “Machine Learning Benchmark” package contains many datasets which can be used for machine learning projects. The Breast Cancer Dataset is also a part of this package.

In the following example we are trying to load a package which we have not installed first. The code will result in an error and rest of the script will not be executed because we had used library() function to load the package.

R




#loading the mlbench package
library(mlbench)
 
#loading Breast Cancer dataset
data(BreastCancer)
 
#view total number of rows in Breast Cancer dataset
nrow(BreastCancer)


Output:

Error in library(mlbench) : there is no package called ‘mlbench’

Load package using require()

Had we used require() to load the package, only a warning message would have been displayed without stopping the execution of the script.

In the following example, we try to load the package using require(). This will produce a warning message saying “there is no package called ‘mlbench’”. Since we have not installed the package, loading the dataset will also produce a warning and finally when we try to count the number of rows in the dataset, we will get an error and the execution will stop.

R




#loading the mlbench package
require(mlbench)
 
#loading Breast Cancer dataset
data(BreastCancer)
 
#view total number of rows in Breast Cancer dataset
nrow(BreastCancer)


Output:

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

Upon comparing the outputs of both the examples, we can see that with require() the execution does not stop and all lines in the script are executed.

  • The main difference between library() and require() is that the library() function will return an error, whereas require() will return a warning message if the package has not been installed.
  • library() method is more suitable to load packages because it will stop the execution and make the developer take necessary actions.

Suitable use of require()

require() returns TRUE if the package is available to be loaded otherwise it returns FALSE. We can use require() to check whether the package that we are trying to load is available or not. For example, if the package is not present then we can either decide to install it or terminate the script.

R




# Storing the return value of require(mlbench) in variable x
x <- require(mlbench)
 
# If the mlbench package is not available, we install and then load it
if(!require(mlbench)) { install.packages("mlbench"); library(mlbench) }


Output:

package ‘mlbench’ successfully unpacked and MD5 sums checked
Warning messages:
1: In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, :
there is no package called ‘mlbench’
2: package ‘mlbench’ was built under R version 4.3.2

Conclusion

In conclusion, both require() and library() in R serve the purpose of loading and attaching packages, but with a key distinction. While library() code execution and throws an error if the package is not available, require() returns a logical value, allowing the script to continue execution. Choose library() for critical dependencies, and require() for conditional loading without interrupting code flow.



Previous Article
Next Article

Similar Reads

How to Plot Timeseries using highcharter library in R
Time series data is a sequence of data points that are measured at regular intervals over time. Plotting time series data is a useful way to visualize trends and patterns over time. Highcharter is an R package that provides an interface to the Highcharts JavaScript charting library. Highcharts is a popular web application library for creating inter
9 min read
Parallel chart with the MASS library in R
To analyze and visualize high-dimensional data, one can use Parallel Coordinates. A background is drawn consisting of n parallel lines, often vertical and evenly spaced, to display a set of points in an n-dimensional space. A point in n-dimensional space is represented by a polyline with vertices on parallel axes; the ith coordinate of the point co
2 min read
How to create SQL table using DBI library in R
DBI library in R programming is used for interacting with different types of database systems such as MySQL for different types of professional work like data analysis using R language. We can easily connect to the database, run queries and retrieve results from the database in the R environment with the DBI library. In this article, we looked at h
3 min read
Difference Between Single and Double Square Brackets in R
The single and double square brackets are used as indexing operators in R Programming Language. Both of these operators are used for referencing the components of R storage objects either as a subset belonging to the same data type or as an element. The table illustrates some key differences among both the types of operators : [] [[]] Used for sing
4 min read
Difference Between as.data.frame() and data.frame() in R
R Programming Language contains a large number of data structures, data frames being very crucial in it. It is used to organize the data in a well-arranged tabular manner. Data frames can both be created from scratch as well as other data objects can be converted to data frames easily using large inbuilt R methods. as.data.frame() The as.data.frame
2 min read
Difference Between R MarkDown and R NoteBook
In this article, we will learn about two very commonly used R interfaces that is R MarkDown and R Notebook then we will also compare the two to analyze the difference between the two. What is R MarkDown? For building dynamic texts in R Programming Language that are simple to share and recreate using the R Markdown file format. It enables you to cre
9 min read
Difference Between & and && in R
In R Programming Language, "&amp;" and "&amp;&amp;" are two logical operators used to combine logical expressions. However, they behave differently in terms of how they evaluate expressions and return results. The "&amp;" operator evaluates both expressions and returns a vector of the same length as the inputs, where each element is the result of a
3 min read
The Difference Between rnorm() and runif() in R
While conducting statistical analysis we generate random numbers for reproducibility and experiments. R Programming Language provides two functions runif() and rnorm() to generate random functions. In this article, we will understand the difference between these two functions and how we can use them with the help of examples. Difference between rno
6 min read
The Difference Between cat() and paste() in R
In R Programming Language efficient data manipulation and string, concatenation are essential for various tasks ranging from data preprocessing to generating informative reports. Two commonly used functions for string manipulation in R are cat() and paste(). While both functions serve similar purposes, they exhibit distinct behaviors and are suited
2 min read
What is the difference between NA and NAN in R?
R Programming Language is a super popular programming language for analyzing data. Lots of data scientists, statisticians, and researchers love using it because it's so versatile and has lots of tools to help them out. But sometimes, figuring out all the little details can't be easy. One thing that often confuses people is understanding the differe
3 min read
Article Tags :