Attach or load packages, and automatically install missing packages if requested
Source:R/packages.R
pkg_attach.Rdpkg_attach() is a vectorized version of library() over
the package argument to attach multiple packages in a single function
call. pkg_load() is a vectorized version of
requireNamespace() to load packages (without attaching them).
The functions pkg_attach2() and pkg_load2() are wrappers of
pkg_attach(install = TRUE) and pkg_load(install = TRUE),
respectively. loadable() is an abbreviation of
requireNamespace(quietly = TRUE). pkg_available() tests if a
package with a minimal version is available.
Usage
pkg_attach(
...,
install = FALSE,
message = getOption("xfun.pkg_attach.message", TRUE)
)
pkg_load(..., error = TRUE, install = FALSE)
loadable(pkg, strict = TRUE, new_session = FALSE)
pkg_available(pkg, version = NULL)
pkg_attach2(...)
pkg_load2(...)Arguments
- ...
Package names (character vectors, and must always be quoted).
- install
Whether to automatically install packages that are not available using
install.packages(). BesidesTRUEandFALSE, the value of this argument can also be a function to install packages (install = TRUEis equivalent toinstall = install.packages), or a character string"pak"(equivalent toinstall = pak::pkg_install, which requires the pak package). You are recommended to set a CRAN mirror in the global optionreposviaoptions()if you want to automatically install packages.- message
Whether to show the package startup messages (if any startup messages are provided in a package).
- error
Whether to signal an error when certain packages cannot be loaded.
- pkg
A single package name.
- strict
If
TRUE, userequireNamespace()to test if a package is loadable; otherwise only check if the package is in.packages(TRUE)(this does not really load the package, so it is less rigorous but on the other hand, it can keep the current R session clean).- new_session
Whether to test if a package is loadable in a new R session. Note that
new_session = TRUEimpliesstrict = TRUE.- version
A minimal version number. If
NULL, only test if a package is available and do not check its version.
Value
pkg_attach() returns NULL invisibly. pkg_load()
returns a logical vector, indicating whether the packages can be loaded.
Details
These are convenience functions that aim to solve these common problems: (1)
We often need to attach or load multiple packages, and it is tedious to type
several library() calls; (2) We are likely to want to install the
packages when attaching/loading them but they have not been installed.
See also
pkg_attach2() is similar to pacman::p_load(), but does
not allow non-standard evaluation (NSE) of the ... argument, i.e.,
you must pass a real character vector of package names to it, and all names
must be quoted. Allowing NSE adds too much complexity with too little gain
(the only gain is that it saves your effort in typing two quotes).