2024

Introduction to External Libraries in R

External libraries in R enhance the functionality by providing additional functions, datasets, and methods that are not available in the base R package.

Installing Libraries

Use the install.packages() function to install new libraries from CRAN (Comprehensive R Archive Network).

install.packages("package_name")
  • This command only needs to be run once per R installation to add the library to your system.

Example: Installing the data.table Package

install.packages("data.table")
  • After installation, the package is permanently available on your machine, until or unless it is explicitly removed.

Loading Libraries

After installation, use the library() or require() function to load the library into your R session.

library(package_name)
  • This command must be run every time you start a new R session and want to use the library.

Example: Loading the data.table Package

library(data.table)
  • Notice that we use data.table with the library() function and we use "data.table" with the install.packages() function.

Installing vs. Loading Libraries

  • Installing a Library: Downloads and installs the package’s files to your R library directory. This is a one-time process for each R installation.

  • Loading a Library: Makes the package’s functions available in your current R session. This must be done every time you start a new session and wish to use the package.

Listing Installed Libraries

You can list all installed libraries using the installed.packages() function.

installed.packages()

Updating Libraries

Keep your libraries up to date to benefit from bug fixes and new features.

update.packages()
  • Optionally, you can specify a package name to update only a specific library.

Removing Libraries

If needed, you can remove installed libraries using the remove.packages() function.

remove.packages("package_name")

Using External Libraries

Once a library is loaded, you can use its functions as if they were part of the base R language.

# Assuming `data.table` is already loaded
library(data.table)

# Create a data table
dt <- data.table(x = c(1, 2, 3), y = c(4, 5, 6))

# Print the data table
print(dt)
##        x     y
##    <num> <num>
## 1:     1     4
## 2:     2     5
## 3:     3     6