Skip to content

Installing and loading R packages

Repositories:

  • CRAN - official R repository
  • Bioconductor - topic specific repository
  • Github - most popular repository for open source projects but not R specific

Package Installation

The commands for the installation of R packages depends on the repository.

### CRAN repository :

install.packages("package")
install.packages(c("packageA", "packageB"))

### Bioconductor:

## R version 3.6+
if (!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")
BiocManager::install("package")

## Older R versions
source("https://bioconductor.org/biocLite.R")
biocLite("package")

### GitHub
library(devtools)
devtools::install_github("link/to/package")

Package Info

It is always a good idea to look at the basic information about a package maybe before but certainly after you have installed it.

packageDescription("package")
help(package = "package")

Manage Packages

# List all installed packages
installed.packages()
# Get Package version
packageVersion("fun")
# Update a package
update.packages("fun")
# Load a package
library("fun")
# Un-load a package
detach("package:fun", unload=TRUE)
# Remove a package
remove.packages("fun")

Example(s)

## Alternative package version

# Install dplyr by installing tidyverse (collection of data science tools):
install.packages("tidyverse")
search()

# Alternatively, install just dplyr:
install.packages("dplyr")

# Or the development version from GitHub:
install.packages("devtools")
devtools::install_github("tidyverse/dplyr")

## Load multiple CRAN packages

# Package list
package.list = c("ggplot2","RColorBrewer","ggpubr")

package.manager <- lapply(
  package.list,
  FUN <- function(x) {
    # Load multiple packages and
    # install missing packages
    if (!require(x, character.only = TRUE)) {
      install.packages(x, dependencies = TRUE)
      library(x, character.only = TRUE)
    }
  }
)

First and Last Lines of any R-Script

This is a personal recommendation for starting and ending an R script.

Before starting a new project, make sure that your workspace (environment) is clean. There should be no leftovers from the previous session that could interfere with your current work. There are brooms for this in Rstudio, and in R scripts you should use rm.

## clean/reset environment
rm(list = ls())

Not all users work with the same extensions and versions. This can lead to conflicts when exchanging R scripts. For this reason, you should summarise your settings in a log file at the end of your R script and include it with your R script. This information is also important for troubleshooting.

## Version 1: Session-Log
writeLines(capture.output(sessionInfo()), "SessionInfo.txt")
## Version 2: Session-Log
sink("SessionInfo.txt")
  sessionInfo()
sink()

Please Code with Style

Save/Load Workspace

# Store your workspace
save.image(file = "myworkspace.RData")
# Restore or load workspace
load("myworkspace.RData")