Efficient way to install and load R packages
The most common method of installing and loading packages is using the install.packages() and library() function respectively. Let us see a brief about these functions –
- Install.packages() is used to install a required package in the R programming language.
Syntax:
install.packages(“package_name”)
- library() is used to load a specific package in R programming language
Syntax:
library(package_name)
In the case where multiple packages have to installed and loaded these commands have to be specified repetitively. Thus making the approach inefficient.
Example:
R
install.packages ( "ggplot2" ) install.packages ( "dplyr" ) install.packages ( "readxl" ) library (ggplot2) library (dplyr) library (readxl) |
Given below are ways by which this can be avoided.
The most efficient way to install the R packages is by installing multiple packages at a time using. For installing multiple packages we need to use install.packages( ) function again but this time we can pass the packages to be installed as a vector or a list with each package separated by comma(,).
Syntax :
install.packages ( c(“package 1″ ,”package 2”, . . . . , “package n”) )
install.packages(“package1″,”package2”, . . . . , “package n”)
Example :
R
install.packages ( c ( "ggplot2" , "dplyr" , "readxl" )) install.packages ( "ggplot2" , "dplyr" , "readxl" ) |
Similarly, package can be loaded efficiently by one of the following ways.
Method 1: Using library()
In this, the packages to be loaded are passed to the function but as a list with each package separated by a comma (,).
Syntax:
library(“package1”, “package2″, . . . . ,”package n”)
Example:
R
library ( "ggplot2" , "dplyr" ) |
Method 2: Using pacman
For efficient package loading, we need to install another package called pacman. To load multiple packages using pacman we use a function called p_load( ).
Syntax :
pacman::p_load( package 1 , . . . . , package n)
Example :
R
pacman:: p_load (dplyr,ggplot2,readxl) |
Please Login to comment...