Open In App

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 –

Syntax:



install.packages(“package_name”)

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:




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 : 




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:




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 :




pacman::p_load(dplyr,ggplot2,readxl)


Article Tags :