Announcement Icon Online training class for Clinical R programming batch starts on Monday, 02Feb2026. Click here for details.

Detach an R package (unload from session)


Lesson Description
-
  • Sometimes we want to remove a package from the current R session—similar to clearing a SAS LIBNAME with LIBNAME mylib CLEAR;
  • detach("package:pkg", unload = TRUE) removes an attached package from the search path and unloads its namespace
  • Check the current search path using search(); attached packages appear as "package:pkg"
  • Meta-packages like tidyverse attach several packages; detach them individually (loop through the tidyverse core packages)
  • Detaching can break objects depending on those functions; prefer a fresh R session for a clean slate during analysis pipelines
#==============================================================================
# Detach a package from the current R session
#==============================================================================

# List attached packages (like seeing active librefs/search path in SAS)
search()

# Detach a single package (example: dplyr)
# Note: Use the 'package:' prefix; unload=TRUE also unloads its namespace
detach("package:dplyr", unload = TRUE)


#==============================================================================
# Caution with meta-packages
#==============================================================================
# 'tidyverse' attaches multiple packages (ggplot2, dplyr, tidyr, readr, etc.).
# Detach each explicitly; there isn't a single 'detach tidyverse' command.
pkgs <- c("ggplot2","tibble","tidyr","readr","purrr","dplyr","stringr","forcats")
attached <- paste0("package:", pkgs)
to_detach <- intersect(attached, search())
for (p in rev(to_detach)) detach(p, unload = TRUE)
# Detach a package from the current R session

# List attached packages
search()

# Detach a single package (example: dplyr)
# Note: Use the 'package:' prefix; unload=TRUE also unloads its namespace

detach("package:dplyr", unload = TRUE)

# Caution with meta-packages
# 'tidyverse' attaches multiple packages (ggplot2, dplyr, tidyr, readr, etc.).
# Detach each explicitly; there isn't a single 'detach tidyverse' command.

pkgs <- c("ggplot2", "tibble", "tidyr", "readr", "purrr", "dplyr", "stringr", "forcats")
attached <- paste0("package:", pkgs)
to_detach <- intersect(attached, search())

for (p in rev(to_detach)) {
  detach(p, unload = TRUE)
}
  • search() lists attached packages.
  • detach("package:pkg", unload = TRUE) removes a package from the session.
  • Loop through attached packages to detach multiple.
  • • R package search path is a stack
    • Detaching must follow reverse attach order
    rev() enforces safe, dependency-aware cleanup
    • Especially critical with meta-packages like tidyverse