The Wayback Machine - https://web.archive.org/web/20241006173828/https://www.geeksforgeeks.org/packages-in-r-programming/
Open In App

Packages in R Programming

Last Updated : 24 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The package is an appropriate way to organize the work and share it with others. Typically, a package will include code (not only R code!), documentation for the package and the functions inside, some tests to check everything works as it should, and data sets. 

Packages in R

Packages in R Programming language are a set of R functions, compiled code, and sample data. These are stored under a directory called “library” within the R environment. By default, R installs a group of packages during installation. Once we start the R console, only the default packages are available by default. Other packages that are already installed need to be loaded explicitly to be utilized by the R program that’s getting to use them. 

What are Repositories?

A repository is a place where packages are located and stored so you can install R packages from it. Organizations and Developers have a local repository, typically they are online and accessible to everyone. Some of the most popular repositories for R packages are: 

  • CRAN: Comprehensive R Archive Network(CRAN) is the official repository, it is a network of FTP and web servers maintained by the R community around the world. The R community coordinates it, and for a package to be published in CRAN, the Package needs to pass several tests to ensure that the package is following CRAN policies.
  • Bioconductor: Bioconductor is a topic-specific repository, intended for open source software for bioinformatics. Similar to CRAN, it has its own submission and review processes, and its community is very active having several conferences and meetings per year in order to maintain quality.
  • Github: Github is the most popular repository for open-source projects. It’s popular as it comes from the unlimited space for open source, the integration with git, a version control software, and its ease to share and collaborate with others.

Get library locations containing R packages

R




.libPaths()


Output:

[1] "C:/Users/GFG19565/AppData/Local/Programs/R/R-4.3.1/library"

This method .libpath() might be related to managing library paths. Library paths are directories where a program looks for external libraries or modules that it needs to import or link during execution.

Get the list of all the R packages installed

R




library()


Output:

Packages in library ‘C:/Users/GFG19565/AppData/Local/Programs/R/R-4.3.1/library’:

abind                       Combine Multidimensional Arrays
ade4                        Analysis of Ecological Data: Exploratory and Euclidean
                            Methods in Environmental Sciences
askpass                     Password Entry Utilities for R, Git, and SSH
backports                   Reimplementations of Functions Introduced Since R-3.0.0
base                        The R Base Package
base64enc                   Tools for base64 encoding
BBmisc                      Miscellaneous Helper Functions for B. Bischl
BH                          Boost C++ Header Files
BiocManager                 Access the Bioconductor Project Package Repository
bit                         Classes and Methods for Fast Memory-Efficient Boolean
                            Selections
bit64                       A S3 Class for Vectors of 64bit Integers
bitops                      Bitwise Operations
blob                        A Simple S3 Class for Representing Vectors of Binary
                            Data ('BLOBS')
boot                        Bootstrap Functions (Originally by Angelo Canty for S)
brew                        Templating Framework for Report Generation
brio                        Basic R Input Output
broom                       Convert Statistical Objects into Tidy Tibbles
bslib                       Custom 'Bootstrap' 'Sass' Themes for 'shiny' and
                            'rmarkdown'
cachem                      Cache R Objects with Automatic Pruning
callr                       Call R from R
car                         Companion to Applied Regression
carData                     Companion to Applied Regression Data Sets
caret                       Classification and Regression Training
caTools                     Tools: Moving Window Statistics, GIF, Base64, ROC AUC,
                            etc

We load a package using library(), the functions and objects in that package become available in the global environment.

Install an R-Packages

There are multiple ways to install R Package, some of them are, 

  • Installing R Packages From CRAN: For installing R Package from CRAN we need the name of the package and use the following command:
install.packages("package name")
  • Installing Package from CRAN is the most common and easiest way as we just have to use only one command. In order to install more than a package at a time, we just have to write them as a character vector in the first argument of the install.packages() function:

Example: 

R




install.packages(c("vioplot", "MASS"))


  • Installing BiocManager Packages: In Bioconductor,using R version 3.5 or greater, which is not compatible with the biocLite.R script for installing Bioconductor packages.

Instead, you should use the BiocManager package to install and manage Bioconductor packages. Here’s an example of how to install the BiocManager package and use it to install a Bioconductor package.

R




install.packages("BiocManager")


This will install some basic functions which are needed to install bioconductor packages, such as the biocLite() function. To install the core packages of Bioconductor just type it without further arguments:

BiocManager::install("edgeR")
  • This will install the edgeR package and its dependencies from the Bioconductor repository.

Update, Remove and Check Installed Packages in R

To check what packages are installed on your computer, type this command: 

installed.packages()

To update all the packages, type this command: 

update.packages()

To update a specific package, type this command: 

install.packages("PACKAGE NAME")

Installing Packages Using RStudio UI

In R Studio goto Tools -> Install Package, and there we will get a pop-up window to type the package you want to install: 

Packages in R ProgrammingGeeksforgeeks

Packages in R Programming

Under Packages, type, and search Package which we want to install and then click on install button. 

How to Load Packages in R Programming Language

When a R package is installed, we are ready to use its functionalities. If we just need a sporadic use of a few functions or data inside a package we can access them with the following notation.

 # Load a package using the library function
   library(dplyr)
# Load a package using the require function
  require(dplyr)

Both functions attempt to load the specified package, but there is a subtle difference between the two: library() returns an error if the package is not found or cannot be loaded, whereas require() returns a warning and sets the value of the package variable to FALSE.

Difference Between a Package and a Library

There is always confusion between a package and a library, and we find people calling libraries as packages. 

  • library(): It is the command used to load a package, and it refers to the place where the package is contained, usually a folder on our computer.
  • Package: It is a collection of functions bundled conveniently. The package is an appropriate way to organize our own work and share it with others.

Load More Than One Package at a Time

We can just input a vector of names to the install.packages() function to install an R package, in the case of the library() function, this is not possible. We can load a set of packages one at a time, or if you prefer, use one of the many workarounds developed by R users. 

In R, you can load more than one package at a time using the library() function. Simply provide the names of the packages you want to load as a vector inside the library() function. Here’s an example:

# Load multiple packages at once
   library(caret, dplyr, ggplot2)

This code loads the caret, dplyr, and ggplot2 packages at once.

Alternatively, you can use the require() function to load multiple packages, but this requires calling the function multiple times, once for each package:

# Load multiple packages using the require function
require(caret)
require(dplyr)
require(ggplot2)

Both methods accomplish the same thing, so it’s mostly a matter of personal preference. The library() function is more concise when loading multiple packages at once, while require() provides more control and can be used to load packages conditionally.

To install an R packages from GitHub from devtools package.

First, you need to install devtools by running the following code:

R




install.packages("devtools")


Output

Packages in R ProgrammingGeeksforgeeks

Packages in R Programming

Once devtools is installed, you can use the install_github() function to install an R package from GitHub. The syntax is:

R




devtools::install_github("github_username/github_repo")


For example, to install the tidyverse package from GitHub, you would run:

R




devtools::install_github("tidyverse/tidyverse")


This will directly download and install the tidyverse package from GitHub.

It should be noted that certain packages may require the installation of extra dependencies before they can be utilised. In this instance, install_github() will attempt to install these dependencies as well. If you run into any problems during the installation, you may try manually installing any missing dependencies with the install.packages() function.

Choose the Right R Packages

The traditional way of discovering R packages is just by learning R, in many tutorials and courses the most popular packages are usually mentioned and used. The first alternative can be to browse categories of CRAN packages. CRAN is the official repository, also gives us the option to browse through packages. 

Another alternative to finding packages can be R Documentation, a help documentation aggregator for R packages from CRAN, BioConductor, and GitHub, which offers you a search box ready for your requests directly on the main page.



Previous Article
Next Article

Similar Reads

Grid and Lattice Packages in R Programming
Every programming language has packages to implement different functions. Many functions are bundled together in a package. To use those functions, installation and loading of these packages are required. In R programming, there are 10, 000 packages in the CRAN repository. Grid and Lattice are some of the packages in R Programming Language which im
3 min read
Get a List of all the Attached Packages in R Programming - search() Function
search() function in R Language is used to get the list of all the attached packages in the R search path. Syntax: search() Parameters: This function takes no parameters. Example 1: # R program to list the packages # attached to R search path # Calling search() function search() Output: [1] ".GlobalEnv" "package:stats" "package:graphics" [4] "packa
1 min read
Get the Full Path of all the Attached Packages in R Programming - searchpath() Function
searchpath() function in R Language is used to list the full path of the packages attached to the R search path. Syntax: searchpath()Parameters: This function takes no parameters. Example 1: C/C++ Code # R program to get the full path # of attached packages in R # Calling searchpath() function searchpath() Output: [1] ".GlobalEnv" [2] "C:/Program F
1 min read
How to Install Multiple R Packages?
In this article, we will see how to install multiple packages in R Programming Language. Installation can be done in two ways. Method 1: Installation using application options Step 1: Open R Studio Step 2: Navigate to Tools and select the Install packages option Step 3: In the Text box packages, enter the package names. Step 4: Click on install but
1 min read
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 p
2 min read
HexBin Plot using hexbin Packages in R
In this article, we are going to see how to plot HexBin Plot using R Programming Language. HexBin plot is also known as hexagonal bin plot and it looks like a honeycomb with different square shading. And each square shading notes with different data points graphed in two dimensions coordinated and square represents a collection of points. To plot H
2 min read
foreach parallel computing using external packages
Parallel computing is a method of breaking down large computational tasks into smaller ones that can be executed simultaneously on multiple processors or cores, leading to faster results. The foreach loop is a popular construct in R programming, which allows users to iterate over a list or vector of elements. In parallel computing, foreach can be u
7 min read
What Are the Tidyverse Packages in R Language?
When dealing with Data Science in the R Programming Language, the Tidyverse packages are your best friends! These Tidyverse packages were specially designed for Data Science with a common design philosophy. They include all the packages required in the data science workflow, ranging from data exploration to data visualization. For example, readr is
10 min read
Updating Packages In R
R is a statistical programming language that relies heavily on the packages and libraries it offers. These packages help with many problems by offering features that make the analysis easier. Updating these packages is crucial to use the new features, bug fixes, or improvements. In this article, we will learn how to update packages in R Programming
5 min read
Which packages in R can we use to do web scraping?
In R, several packages can be used for web scraping, with rvest, httr, and xml2 being among the most popular. These packages allow users to download and parse web pages, extract specific data, and handle various aspects of web scraping effectively. Each of these packages has unique features that make them suitable for different types of web scrapin
2 min read
Fundamental Difference Between jsonlite and rjson Packages
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In R, several packages are available for handling JSON data, with jsonlite and rjson being two of the most popular ones. Both packages are used to convert between R objects and JSON strin
4 min read
Developing R Packages from Scratch
R is considered as a powerful language for statistical computing, machine learning and and data analysis. Its major strength lies in the way that it allows its users to develop their own packages. Creating an R package from scratch can seem as a hectic task, but with a structured approach, it becomes interesting to create and at the same time, it b
5 min read
What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
Getting the Modulus of the Determinant of a Matrix in R Programming - determinant() Function
determinant() function in R Language is a generic function that returns separately the modulus of the determinant, optionally on the logarithm scale, and the sign of the determinant. Syntax: determinant(x, logarithm = TRUE, ...) Parameters: x: matrix logarithm: if TRUE (default) return the logarithm of the modulus of the determinant Example 1: # R
2 min read
tidyr Package in R Programming
Packages in the R language are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the tidyr package. The sole purpose of the tidyr package is to simplify the proc
14 min read
Get Exclusive Elements between Two Objects in R Programming - setdiff() Function
setdiff() function in R Programming Language is used to find the elements which are in the first Object but not in the second Object. Syntax: setdiff(x, y) Parameters: x and y: Objects with sequence of itemsR - setdiff() Function ExampleExample 1: Apply setdiff to Numeric Vectors in R Language C/C++ Code # R program to illustrate # the use of setdi
2 min read
Add Leading Zeros to the Elements of a Vector in R Programming - Using paste0() and sprintf() Function
paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. Syntax: paste0("0", vec) or sprintf("%0d", vec)Parameters: paste0: It will add zeros to vector sprintf: To format a vector(adding zeros) vec: Original vector dataReturns: Vectors by addition of leading zeros Exa
1 min read
Clustering in R Programming
Clustering in R Programming Language is an unsupervised learning technique in which the data set is partitioned into several groups called clusters based on their similarity. Several clusters of data are produced after the segmentation of data. All the objects in a cluster share common characteristics. During data mining and analysis, clustering is
6 min read
Compute Variance and Standard Deviation of a value in R Programming - var() and sd() Function
var() function in R Language computes the sample variance of a vector. It is the measure of how much value is away from the mean value. Syntax: var(x) Parameters: x : numeric vector Example 1: Computing variance of a vector # R program to illustrate # variance of vector # Create example vector x <- c(1, 2, 3, 4, 5, 6, 7) # Apply var function in
1 min read
Compute Density of the Distribution Function in R Programming - dunif() Function
dunif() function in R Language is used to provide the density of the distribution function. Syntax: dunif(x, min = 0, max = 1, log = FALSE) Parameters: x: represents vector min, max: represents lower and upper limits of the distribution log: represents logical value for probabilities Example 1: # Create vector of random deviation u <- runif(20)
1 min read
Compute Randomly Drawn F Density in R Programming - rf() Function
rf() function in R Language is used to compute random density for F Distribution. Syntax: rf(N, df1, df2) Parameters: N: Sample Size df: Degree of Freedom Example 1: # R Program to compute random values # of F Density # Setting seed for # random number generation set.seed(1000) # Set sample size N <- 20 # Calling rf() Function y <- rf(N, df1
1 min read
Data Handling in R Programming
R Programming Language is used for statistics and data analytics purposes. Importing and exporting of data is often used in all these applications of R programming. R language has the ability to read different types of files such as comma-separated values (CSV) files, text files, excel sheets and files, SPSS files, SAS files, etc. R allows its user
5 min read
Return a Matrix with Lower Triangle as TRUE values in R Programming - lower.tri() Function
lower.tri() function in R Language is used to return a matrix of logical values with lower triangle as TRUE. Syntax: lower.tri(x, diag) Parameters: x: Matrix object diag: Boolean value to include diagonal Example 1: # R program to print the # lower triangle of a matrix # Creating a matrix mat <- matrix(c(1:9), 3, 3, byrow = T) # Calling lower.tr
1 min read
Print the Value of an Object in R Programming - identity() Function
identity() function in R Language is used to print the value of the object which is passed to it as argument. Syntax: identity(x) Parameters: x: An Object Example 1: # R program to print # the value of an object # Creating a vector x <- c(1, 2, 3, 4) # Creating a list list1 <- list(letters[1:6]) # Calling the identity function identity(x) ide
1 min read
Check if Two Objects are Equal in R Programming - setequal() Function
setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not. Syntax: setequal(x, y) Parameters: x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of setequal(
1 min read
Random Forest with Parallel Computing in R Programming
Random Forest in R Programming is basically a bagging technique. From the name we can clearly interpret that this algorithm basically creates the forest with a lot of trees. It is a supervised classification algorithm. In a general scenario, if we have a greater number of trees in a forest it gives the best aesthetic appeal to all and is counted as
4 min read
R - Object Oriented Programming
In this article, we will discuss Object-Oriented Programming (OOPs) in R Programming Language. We will discuss the S3 and S4 classes, the inheritance in these classes, and the methods provided by these classes. OOPs in R Programming Language:In R programming, OOPs in R provide classes and objects as its key tools to reduce and manage the complexity
7 min read
Check for Presence of Common Elements between Objects in R Programming - is.element() Function
is.element() function in R Language is used to check if elements of first Objects are present in second Object or not. It returns TRUE for each equal value. Syntax: is.element(x, y) Parameters: x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of is.element() function # Vector 1 x1 <- c(1, 2, 3) # Vector 2 x2
1 min read
AB Testing With R Programming
Split testing is another name of A/B testing and it's a common or general methodology. It's used online when one wants to test a new feature or a product. The main agenda over here is to design an experiment that gives repeatable results and robust to make an informed decision to launch it or not. Generally, this test includes a comparison of two w
7 min read
Check if Elements of a Vector are non-empty Strings in R Programming - nzchar() Function
nzchar() function in R Language is used to test whether elements of a character vector are non-empty strings. Syntax: nzchar(x) Parameters: x: character vector Example 1: # R program to illustrate # nzchar function # Initializing a character vector x <- c("GFG", "gfg") y <- c("a", "b", "c") #
1 min read
Article Tags :