Written and maintained by CASRAI Editorial Board
Published
On this page
To view loaded packages in R, run sessionInfo() in the R console to display all attached packages and imported namespaces alongside their exact version numbers, or call search() to list packages currently attached to the active search path. While search() reveals the environments whose functions can be invoked directly without package prefixing, loadedNamespaces() exposes every namespace resident in memory, including upstream dependencies loaded in the background by other libraries.
What it is used for in research
In scientific computing and empirical data analysis, inspecting loaded packages is an essential discipline for maintaining computational reproducibility and research integrity. Academic workflows frequently involve multifaceted analytical pipelines spanning data cleaning, biostatistical modeling, and publication-grade visualization. When analyses rely on statistical packages that evolve over time, subtle differences between minor package versions can alter numerical convergence thresholds, default parameter values, or random seed handling. Verifying loaded packages ensures researchers know the exact software state that produced a given set of empirical findings.
Inspecting active packages is foundational to reproducible research practices. Funding agencies and peer-reviewed journals increasingly mandate comprehensive methodological transparency. Under contemporary open science standards, sharing raw code is insufficient unless the computational environment is also documented. Capturing loaded packages and their underlying dependencies allows external peer reviewers and independent laboratory teams to reconstruct the computational environment, verify statistical claims, and eliminate environment-specific discrepancy.
Furthermore, monitoring loaded packages prevents silent function collisions. In large collaborative projects where multiple team members contribute code scripts, loading overlapping packages can result in later packages masking critical functions from earlier packages. For example, loading data manipulation tools can mask base R modeling or filtering commands. Regularly querying the active session enables analysts to detect collisions immediately, establish explicit namespace routing, and verify package provenance before executing mission-critical statistical models.
Attached packages versus loaded namespaces
A frequent source of confusion among R programmers is the architectural distinction between attached packages and loaded namespaces. R manages code isolation through a formal namespace mechanism defined in the base execution system. Understanding how R differentiates these states is crucial for interpreting session output correctly.
An attached package is placed directly onto R search path, which is queried sequentially by the interpreter whenever an unqualified function name is evaluated. When an analyst executes library(dplyr) or require(MASS), R executes two distinct actions: it loads the package namespace into memory and attaches the package environment to the search path at position 2 (immediately after the user global environment, .GlobalEnv). Any exported function in an attached package can be invoked directly by name without package prefixes.
A loaded namespace, by contrast, resides in memory but is not attached to the search path. A package enters this state when it is loaded as an upstream dependency declared in another package Imports field, or when an analyst invokes a function using the explicit double-colon operator, such as readr::read_csv(), without running library(readr). Functions in a loaded-only namespace cannot be invoked without their prefix, and their internal objects do not participate in standard search-path lookup. Calling loadedNamespaces() returns all packages in memory, encompassing both attached libraries and unattached background dependencies.
Install or access
The primary functions required to inspect loaded packages and session environments in R are built directly into the core runtime system. Functions including sessionInfo(), search(), searchpaths(), loadedNamespaces(), .packages(), and conflicts() are distributed as standard components of the base and utils packages. They are available immediately upon installing R and RStudio without requiring any secondary installation or external network access.
For enhanced session auditing, researchers frequently install extended inspection packages from the Comprehensive R Archive Network (CRAN). The sessioninfo package, developed by the r-lib team, provides an advanced diagnostic alternative that formats package origins, GitHub commit hashes, and underlying operating system libraries. Researchers can install this tool through the standard package management interface:
# Install enhanced session reporting tool from CRAN
install.packages("sessioninfo")
# Verify access in the current R console
packageVersion("sessioninfo")
Comprehensive guidance on compiling and installing external software packages across varied platforms can be reviewed in our companion guide on installing R libraries.
Step-by-step task: Inspecting loaded packages in R
Researchers can systematically audit, list, and verify packages loaded in an active R session by following these six procedural steps. All commands can be executed in the interactive R console, an RStudio terminal pane, or within automated R Markdown and Quarto compilation scripts.
- Inspect attached packages on the active search path: Run the
search()function to list all environments and libraries currently searched for unqualified symbols:# List attached environments search()To retrieve only the clean character vector of attached package names without the
package:prefix, execute the internal base utility:# List attached package names only .packages() - List all loaded namespaces resident in memory: Query the runtime namespace registry to expose all packages loaded in memory, including hidden background imports:
# List all loaded namespaces loadedNamespaces()To check whether a specific library namespace is currently loaded in memory without altering the search path, use the boolean predicate:
# Check if a specific namespace is loaded isNamespaceLoaded("ggplot2") - Generate a complete session diagnostics report: Call
sessionInfo()to generate an official diagnostic summary that details base packages, attached packages, and loaded namespaces:# Print full session information sessionInfo() - Inspect exact version numbers and package metadata: Query specific libraries to confirm exact version strings and build dates:
# Query version of an attached or loaded library packageVersion("stats") # Read complete DESCRIPTION metadata packageDescription("utils", fields = c("Version", "Built", "Priority")) - Verify library installation paths on disk: Confirm the physical directory locations from which attached packages were loaded into memory, ensuring no unintended library tree was accessed:
# Display filesystem paths for attached environments searchpaths() # Display configured library directories .libPaths() - Detect symbol masking and namespace conflicts: Run
conflicts()to identify functions in newly loaded packages that mask identically named functions in earlier packages:# Audit masking conflicts across the search path conflicts(detail = TRUE)
Output and how to read it
Accurately reading R session diagnostics requires interpreting the distinct sections generated by inspection commands. Understanding how each block of information maps to the underlying R runtime enables researchers to spot configuration errors rapidly.
When invoking sessionInfo(), the output is partitioned into several distinct blocks:
- R runtime and operating system metadata: The initial lines report the exact R version (e.g., R version 4.4.1), platform architecture (e.g., x86_64-pc-linux-gnu), running operating system, and active locale settings. It also reports the specific BLAS and LAPACK numerical linear algebra libraries linked to the binary, which directly influence numerical precision in matrix decompositions.
- Attached base packages: Lists standard core packages attached automatically at startup (such as
stats,graphics,grDevices,utils,datasets,methods, andbase). - Other attached packages: Displays packages explicitly attached by the user via
library()orrequire(). Each entry is printed with its version string (e.g.,dplyr_1.1.4,ggplot2_3.5.1). These packages reside on the active search path. - Loaded via a namespace (and not attached): Enumerates all secondary libraries present in memory that provide helper functions, S3/S4 method dispatch tables, or internal C bindings. While their functions are not exposed on the global search path, their version numbers remain recorded here for complete auditability.
When reading the output of search(), elements are ordered by search priority. Position 1 is always .GlobalEnv, where user-defined variables and functions live. When a new package is attached via library(), it is inserted at position 2, pushing previous packages further down the chain. The base package environment, package:base, always occupies the final position. If two packages define a function with identical spelling, R selects the function belonging to the package positioned higher on the search path.
When examining modern diagnostics via sessioninfo::session_info(), researchers obtain additional provenance data. In addition to package names and versions, the tool outputs an explicit source column showing whether each package originated from CRAN, Bioconductor, a GitHub repository with commit SHA, or a local development directory. This detailed breakdown is particularly valuable when working with development builds managed via the devtools package for R.
Troubleshooting package and namespace conflicts
Session inspection often uncovers unexpected behavior in statistical routines. Common package management issues and their technical resolutions include the following scenarios:
Function masking and unintentional overrides
The most frequent problem in multi-package workflows occurs when a package masks a core function. For example, attaching the dplyr package masks filter() and lag() from the base stats package. If legacy modeling scripts call filter() expecting time-series filtering, the code will fail with syntax errors. To resolve this, researchers can inspect collisions using conflicts(detail = TRUE) and bypass the search path entirely by qualifying calls with package names, writing stats::filter() or dplyr::filter().
Safely detaching packages from the search path
If a package is no longer needed or causes naming conflicts, analysts can remove it from the active search path using detach(). To ensure the package namespace is also unloaded from memory, pass the unload = TRUE argument:
# Detach package from search path and unload namespace
detach("package:MASS", unload = TRUE)
If another loaded package depends on the library being detached, R will issue a warning or prevent unloading. In such cases, dependent packages must be detached first, or the analyst should restart the R session.
Resolving locked namespace errors
Attempting to unload a namespace with unloadNamespace("pkgname") can produce the error: namespace is imported by … and cannot be unloaded. This occurs when an active package has registered imports pointing to that namespace. The safest resolution in interactive work is to restart the R session (in RStudio: Session → Restart R or Ctrl+Shift+F10). In automated pipelines, running analyses in clean, isolated batch processes via Rscript prevents namespace contamination between consecutive jobs.
Workspace contamination from saved environments
By default, R may prompt users to save workspace images to .RData upon exiting. Loading an existing .RData file restores previous objects into .GlobalEnv, which can mask package functions and pre-populate attached package states. In reproducible scientific pipelines, researchers should always launch R with the --vanilla or --no-save --no-restore flags to guarantee an entirely blank session state. Researchers seeking to inspect sample datasets pre-bundled inside loaded libraries can consult our guide on datasets in R packages.
Programmatic logging for reproducible pipelines
Capturing session status interactively is useful during exploratory analysis, but production research workflows require automated, scriptable logging. Integrating package inspection routines directly into analysis scripts ensures that every generated plot, statistical table, and manuscript figure is accompanied by an immutable software record.
A standard programmatic pattern captures sessionInfo() text output and saves it directly alongside analytical artifacts:
# Programmatic logging pattern for scientific scripts
log_session_manifest <- function(output_path = "session_environment.txt") {
info <- utils::sessionInfo()
sink(output_path)
on.exit(sink())
cat("=== COMPUTATIONAL SESSION LOG ===n")
cat("Timestamp:", format(Sys.time(), "%Y-%m-%d %H:%M:%S %Z"), "n")
cat("Working Directory:", getwd(), "nn")
print(info)
}
# Execute at conclusion of data analysis script
log_session_manifest("results/session_manifest.txt")
For automated processing in continuous integration or pipeline orchestrators, researchers can extract attached packages and version numbers into structured data frames:
# Extract attached packages and versions programmatically
get_attached_manifest <- function() {
pkgs <- .packages()
data.frame(
package = pkgs,
version = vapply(pkgs, function(p) as.character(utils::packageVersion(p)), character(1)),
stringsAsFactors = FALSE,
row.names = NULL
)
}
# Inspect clean tabular summary
print(get_attached_manifest())
When publishing research compendia, embedding this programmatic summary in reproducible dynamic documents (such as Quarto or R Markdown) ensures reviewers can instantly inspect package states at the footer of the compiled report.
Free alternatives
Researchers have access to several open-source tools and frameworks for inspecting, recording, and isolating software environments in R and adjacent computational stacks. The data table below compares primary inspection and environment tracking utilities available across the scientific computing ecosystem.
| Tool or Function | Ecosystem | Primary Inspection Scope | Lockfile Generation | Licensing |
|---|---|---|---|---|
| utils::sessionInfo() | Base R runtime | Attached packages, loaded namespaces, R core version, and BLAS/LAPACK | No (text report only) | GPL-2 / GPL-3 |
| sessioninfo::session_info() | R CRAN (r-lib) | Attached packages, loaded namespaces, package repository sources, and system libraries | No (extended text report) | GPL-2 |
| renv::status() / snapshot() | R CRAN (Posit) | Project-level package dependencies, version lockfiles, and library cache status | Yes (renv.lock JSON file) | MIT |
| pip list / pip freeze | Python / PyPA | Installed Python distribution packages and exact version strings | Yes (requirements.txt) | MIT |
| conda list | Conda / Mamba | Cross-language binary packages, channel origins, and build strings | Yes (environment.yml) | BSD-3-Clause |
| GNU Guix / Nix | Linux system level | Complete operating system environment, compilers, and user libraries | Yes (declarative manifest) | GPL-3+ / MIT |
For ad-hoc script exploration, utils::sessionInfo() remains the most portable solution because it requires zero setup. For comprehensive long-term scientific projects, integrating session inspection with package pinning tools such as renv provides end-to-end reproducibility across operating systems.
Frequently asked questions
What is the difference between attached packages and loaded namespaces in R?
Attached packages reside directly on R search path, allowing their exported functions to be invoked by name without package prefixing. Loaded namespaces reside in memory but are not attached to the search path; their functions can only be invoked using the double-colon notation (such as package::function()) or called internally by other packages that import them.
How do I check which packages are currently loaded in R?
To check all packages loaded in memory, execute loadedNamespaces() in the R console. To view only the packages currently attached to the active search path, execute search() or .packages(). For a complete diagnostic breakdown including version numbers and system architecture, run sessionInfo().
How do I see the package version of a loaded library in R?
You can check the version of any loaded or installed package by running packageVersion("package_name"). Alternatively, running sessionInfo() prints the version strings for all attached packages under the other attached packages header and all loaded background libraries under the loaded via a namespace header.
Why does a function behave differently after loading a new package in R?
This discrepancy is typically caused by function masking. When a new package is attached via library(), it is placed near the front of the search path, overriding identically named functions from earlier packages or base R. You can inspect masked functions across your session using conflicts(detail = TRUE) and resolve collisions by specifying the exact package namespace explicitly, such as stats::filter() instead of filter().
How do I unload or detach a package without restarting R?
To remove an attached package from the search path and attempt to unload its namespace from memory, execute detach("package:package_name", unload = TRUE). If other active libraries import that package, R will prevent unloading; in that scenario, dependent packages must be detached first or the R session restarted.
Does require() attach a package differently than library()?
Both library() and require() attach packages to the search path in an identical manner. The difference lies in error handling: library() halts execution with a fatal error if the requested package is missing, whereas require() emits a warning and returns FALSE, making it suitable for conditional statements inside programmatic functions.
How do I list only user-installed loaded packages excluding base R?
To isolate user-loaded libraries, query sessionInfo()$otherPkgs, which contains a named list of non-base attached packages. In code, running names(sessionInfo()$otherPkgs) returns a character vector containing only user-attached libraries, excluding default base components like stats and utils.
Sources
- R Core Team. (2024). sessionInfo: Collect Information About the Current R Session. R utils package manual. https://stat.ethz.ch/R-manual/R-devel/library/utils/html/sessionInfo.html (Accessed 2026-11-15)
- R Core Team. (2024). search: Give Search Path for R Objects. R base package manual. https://stat.ethz.ch/R-manual/R-devel/library/base/html/search.html (Accessed 2026-11-15)
- R Core Team. (2024). ns-load: Loading and Unloading Name Spaces. R base package manual. https://stat.ethz.ch/R-manual/R-devel/library/base/html/ns-load.html (Accessed 2026-11-15)
- R Core Team. (2024). .packages: Listing Packages. R base package manual. https://stat.ethz.ch/R-manual/R-devel/library/base/html/packages.html (Accessed 2026-11-15)
- R Core Team. (2024). detach: Detach Objects from the Search Path. R base package manual. https://stat.ethz.ch/R-manual/R-devel/library/base/html/detach.html (Accessed 2026-11-15)
- R Core Team. (2024). conflicts: Search for Masked Objects on the Search Path. R base package manual. https://stat.ethz.ch/R-manual/R-devel/library/base/html/conflicts.html (Accessed 2026-11-15)
- R Core Team. (2024). packageDescription: Package Description and Version. R utils package manual. https://stat.ethz.ch/R-manual/R-devel/library/utils/html/packageDescription.html (Accessed 2026-11-15)
- Csardi, G., Hester, J., Wickham, H., et al. (2024). sessioninfo: R Session Information. r-lib manual. https://sessioninfo.r-lib.org/ (Accessed 2026-11-15)
Data: R Session Package and Namespace Inspection Functions Comparison
Comparative matrix of standard and extended R functions used to inspect loaded packages, resident namespaces, and search-path environments. Compiled from official R manuals and r-lib documentation.
Period covered: 2024/2026. Coverage: Global.
| Inspection Command | Package Environment | Inspection Scope | Reports Package Versions | Distinguishes Attached vs Loaded | Primary Output Class | Relative Execution Overhead |
|---|---|---|---|---|---|---|
| sessionInfo() | utils | Attached packages and loaded namespaces with system runtime | Yes | Yes | sessionInfo | Moderate |
| search() | base | Attached packages and user environments on search path | No | No | character | Low |
| searchpaths() | base | Filesystem directory paths of attached environments | No | No | character | Low |
| loadedNamespaces() | base | All loaded namespaces resident in memory | No | No | character | Low |
| .packages() | base | Package names currently attached to search path | No | No | character | Low |
| conflicts(detail = TRUE) | base | Masked symbols across attached package environments | No | No | list | Moderate |
| sessioninfo::session_info() | sessioninfo | Attached packages, loaded namespaces, source repositories, and OS libraries | Yes | Yes | session_info | Moderate |
Sources
- R utils package sessionInfo documentation (accessed 2026-11-15)
- R base package search documentation (accessed 2026-11-15)
- R base package ns-load documentation (accessed 2026-11-15)
- R base package conflicts documentation (accessed 2026-11-15)
- sessioninfo package documentation (accessed 2026-11-15)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







