R packages consists of a collection of R functions, data sets and compiled code which adds value to the existing R-functionalities. They are stored in the 'library' directory in the R-environment and developed by the community. For Example, "dplyr" is one of the commonly used packages in R which adds further functionalities with respect to working with dataframes.
There already exists some default packages in the local directory 'library' on your machine when you install R. We can all the default packages by using code : 'library()'. It is very crucial to load the package before using it in code. And this can be done in two ways:
This recipe demonstrates the two different ways to load a package after installation.
We use the command " install.packages("name of the package") " to install the package
After running the command, you might recieve some messages which is based on the OS, dpendencies installed and the status of the package.
The most commonly used function to load the package is library(). require() is only used when we have to use the logical values that it returns. It will return TRUE if the package is present and successfully loaded. It is used in a error checking loop given by thierry.
Loading required package: MASS Warning message: "package 'MASS' was built under R version 3.6.3"
Warning message: "package 'MASS' was built under R version 3.6.3"
We will store and display the output of the two functions by using an invalid package name to check for error.
test1 = library("abc")
Error in library("abc"): there is no package called 'abc' Traceback: 1. library("abc")
Error in eval(expr, envir, enclos): object 'test1' not found Traceback:
test2 = 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'"
From the the above two tests, we can see that test2 (require()) returns a logical value FALSE when an error was occurred while test1 (library()) object was not created when error had occurred. Hence, require() is only used when the returned logical value needs to be used.