Introduction and notation
This vignette explains how to install R packages; how to get information about to-be-installed and already-installed R packages; and how to get the source code of R functions.
Text between angled brackets (<...>) is used to
refer to text that should be replaced with specific text to get working
code or working file paths. For example, <pkg> is
used as a place holder to refer to a package name and should be replaced
with utils if you want to get information about package
utils, and with methods if you want to get
information about package methods. Similarly,
<func> is used as a place holder to refer to a
function name that should be replaced with a specific function name to
get working code.
In this vignette, calls to functions are frequently written in the
form <pkg>::<func>(), to make clear which
package is used and, through the brackets, that a function is indicated.
In normal scripts, one would use library(<pkg>) in a
section at the top of the script where all required packages are loaded,
followed by <func>() where that is needed. For
example, in this vignette the notation utils::citation() is
used to show how to cite R, indicating that the function
citation() is defined in package utils. In
normal scripts, one would use library(utils) in a section
at the top of the script, followed by citation() where that
is needed.
R packages
An R package is a standardized collection of material extending R by providing code, data, or documentation.
The base
packages are always installed together with R. The recommended
packages are installed with binary distributions of R. Together, the
base and recommended packages are the ‘high priority’ packages. Since R
4.4.0, tools::standard_package_names() contains a list with
the names of these packages. To see which high-priority packages are
currently installed, run
sort(unname(installed.packages(priority = "high")[, "Package"])).
Package translations is not a recommended package, but will
be installed if that option is set during the installation of R.
Installing packages
To install a package, run R or RStudio as administrator: right-click
on the R or RStudio icon and select Run as administrator.
Packages can be obtained from several websites, called ‘repositories’,
such as CRAN, Bioconductor, and
GitHub, discussed in the next sections. After installing a
package, you need to attach it to be able to use
its functions: run library(<pkg>).
CRAN
The Comprehensive R Archive Network (CRAN) is the main repository of R packages. The following code can be used to install packages from CRAN:
pkgs_new <- c(<pkg>, <pkg>)
# Select packages from 'pkgs_new' that are not installed or not functional
pkgs_install <- pkgs_new[!vapply(X = pkgs_new, FUN = requireNamespace,
FUN.VALUE = logical(1), quietly = TRUE)]
if(length(pkgs_install) > 0L) {
install.packages(pkgs = pkgs_install, lib = .libPaths(), dependencies = NA,
type = getOption("pkgType"), verbose = getOption("verbose"),
quiet = FALSE)
}CRAN has thematic package collections known as task views. To install
all core packages of a task view, install package ctv and
run
ctv::install.views("<taskview>", coreOnly = TRUE). To
update these packages, use
ctv::update.views("<taskview>", coreOnly = TRUE).
utils::available.packages() gives information about
packages available from CRAN.
tools::CRAN_package_db() gives much more information for
each package, including the Description and
Maintainer fields not returned by
utils::available.packages().
tools::CRAN_package_db() also includes the development
versions of the recommended
packages, which have "4.7.0/Recommended" instead of
<NA> in column Path.
tools::CRAN_check_results() gives information about the
current check status of CRAN packages. Packages from CRAN that have been
recently archived, for example because check issues were not addressed
in time, are available at CRANhaven.
Bioconductor
The Bioconductor repository hosts many R packages related to bioinformatics. Bioconductor has a new release every six months. Each release contains specific versions of packages from CRAN and Bioconductor that are consistent with each other and with a specific version of R, preventing version conflicts between R packages.
The following code can be used to install packages from Bioconductor
release version
3.23. This code installs the BiocManager
package from CRAN that is then
used to install packages from Bioconductor and CRAN and,
through remotes::install_github() (see the next section), from GitHub:
pkgs_new <- c(<pkg>, <pkg>)
if(!requireNamespace("BiocManager", quietly = TRUE)) {
install.packages(pkgs = "BiocManager", lib = .libPaths(), dependencies = NA,
type = getOption("pkgType"), verbose = getOption("verbose"),
quiet = FALSE)
}
BiocManager::install(pkgs = pkgs_new, lib = .libPaths(), dependencies = NA,
build_vignettes = TRUE,
type = getOption("pkgType"), verbose = getOption("verbose"),
update = FALSE, ask = TRUE, checkBuilt = TRUE,
force = FALSE, version = "3.23")Bioconductor also has thematic package collections known as BiocViews.
utils::available.packages(repos = BiocManager::repositories())
gives information about packages available from Bioconductor,
and BiocManager::available() gives their names.
Github
The following code can be used to install packages from GitHub: it installs the remotes
package that is used to install packages from GitHub, selects those
elements of pkgs_new that give the author name and
repository name (e.g., "JesseAlderliesten/checkrpkgs") or
the full URL to a package (e.g.,
"https://github.com/JesseAlderliesten/checkrpkgs") as
required by remotes::install_github(), and installs those
packages. To match such names to package names as returned by
utils::installed.packages(), use
basename(pkgs_new) to select the last part of those names:
pkgs_new[!(basename(pkgs_new) %in% installed.packages()[, "Package"])].
pkgs_new <- "JesseAlderliesten/checkrpkgs"
if(!requireNamespace("remotes", quietly = TRUE)) {
install.packages(pkgs = "remotes", lib = .libPaths(), dependencies = NA,
type = getOption("pkgType"), verbose = getOption("verbose"),
quiet = FALSE)
}
remotes::install_github(repo = grep(pattern = "/", x = pkgs_new, value = TRUE),
dependencies = NA, upgrade = "ask", force = FALSE,
quiet = FALSE, build_vignettes = TRUE, lib = .libPaths(),
verbose = getOption("verbose"))Other repositories
Examples of other repositories for R packages are:
- Neuroconductor
- R-Forge with a GitHub mirror and thematic package collections
- R-multiverse with thematic package collections
- rOpenSci with thematic package collections
-
R universe with an overview of datasets (see
help("data", package = "utils")) included in R packages
Repositories can be selected using
utils::setRepositories(). The websites of these
repositories include instructions how to install packages from them. In
addition, package remotes
contains functions to install packages from some of these repositories.
The following code shows how to install packages from R-Forge as an example:
pkgs_new <- c(<pkg>, <pkg>)
# Select packages from 'pkgs_new' that are not installed or not functional
pkgs_install <- pkgs_new[!vapply(X = pkgs_new, FUN = requireNamespace,
FUN.VALUE = logical(1), quietly = TRUE)]
if(length(pkgs_install) > 0L) {
install.packages(pkgs = pkgs_install, lib = .libPaths(),
repos = "https://r-forge.r-project.org/", dependencies = NA,
type = getOption("pkgType"), verbose = getOption("verbose"),
quiet = FALSE)
}Mirror websites
Mirror websites (‘mirrors’) are websites hosted in various parts of
the world with the same content as the main website. Using a nearby
mirror allows for faster downloads. Mirrors of repositories can be
selected using utils::setRepositories(), which in the
documentation also mentions options("repos"),
options("BioC_mirror") and the environment variable
R_REPOSITORIES (the value of which is shown by
Sys.getenv("R_REPOSITORIES")).
CRAN mirrors,
with information about their status that is
also available from within R through
utils::getCRANmirrors(), can be selected using
utils::chooseCRANmirror(). However, RStudio uses
the RStudio CRAN mirror with its
own global distribution, which is signalled by the message
'getOption("repos")' replaces Bioconductor standard repositories, see 'help("repositories", package = "BiocManager")' for details.
Bioconductor mirrors, with
information about their status, can
be selected using BiocManager::repositories() or
utils::chooseBioCmirror(), although the RStudio CRAN mirror
is used in RStudio (see the preceding paragraph).
Loading and attaching packages
After installing a package, you need to load the namespace of a
package and attach the package to the search list to be able to use its
functions: run library(<pkg>). If this fails without
clear reason, setting environment variable
_R_TRACE_LOADNAMESPACE_ to a numerical value (e.g.,
Sys.setenv("_R_TRACE_LOADNAMESPACE_" = 4)) will generate
additional messages on progress for non-standard packages (see the
section Tracing in
help("requireNamespace")).
loadedNamespaces() gives the names of packages that are
currently loaded, utils::sessionInfo() also gives their
versions, path.package() gives the paths from which
packages were loaded. sessioninfo::session_info() provides
the names, versions and the paths of loaded packages, and has the option
to show information about their dependencies (and returns the names in
alphabetical order instead of the order of loading).
options("defaultPackages") gives the names of packages that
are attached by default when R starts up if environment variable
R_DEFAULT_PACKAGES is unset (i.e.,
Sys.getenv("R_DEFAULT_PACKAGES") is "", see
help("Startup") and the entry defaultPackages
in help(options)).
Updating packages
Updating out-of-date packages prevents compatibility issues between already-installed and newly-installed packages.
CRAN
For R packages from CRAN, versions can be compared using diffify and a chronological overview of changes is available at CRANberries.
Package rcheology
provides an overview of functions in earlier versions of base R. Package
backports
provides re-implementations of old functions.
To get the version number of an installed package, run
utils::packageVersion("<pkg>").
old.packages() indicates which packages can be updated.
The following code can be used to install the latest version of packages from CRAN (this changes the version of already-installed packages, which might be undesirable):
utils::update.packages(lib.loc = .libPaths(), ask = TRUE, dependencies = NA,
verbose = getOption("verbose"), quiet = FALSE,
checkBuilt = TRUE, type = getOption("pkgType"))Bioconductor
BiocManager::valid() indicates which packages can be
updated and also checks for too new packages, taking the currently used
version of Bioconductor (see BiocManager::version()) into
account. The following code can be used to update packages to a specific
Bioconductor release (here version 3.23):
if(!requireNamespace("BiocManager", quietly = TRUE)) {
install.packages(pkgs = "BiocManager", lib = .libPaths(), dependencies = NA,
type = getOption("pkgType"), verbose = getOption("verbose"),
quiet = FALSE)
}
BiocManager::install(pkgs = character(), lib = .libPaths(), dependencies = NA,
build_vignettes = TRUE,
type = getOption("pkgType"), verbose = getOption("verbose"),
update = TRUE, ask = TRUE, checkBuilt = TRUE, force = FALSE,
version = "3.23")Installing old versions
Installing old versions of a package might require installing Rtools
to build the packages from source, see the section Rtools
in the vignette Installing R, Rtools and RStudio:
vignette("install_r", package = "checkrpkgs").
CRAN
The following code can be used to install an old version of a package
from CRAN, using package remotes:
if(!requireNamespace("remotes", quietly = TRUE)) {
install.packages(pkgs = "remotes", lib = .libPaths(), dependencies = NA,
type = getOption("pkgType"), verbose = getOption("verbose"),
quiet = FALSE)
}
remotes::install_version(package = "deSolve", version = "1.40", dependencies = NA,
upgrade = "ask", quiet = FALSE, build_vignettes = TRUE,
lib = .libPaths(), verbose = getOption("verbose"))It is also possible to specify minimum versions, e.g.,
version = >= 1.40.
Alternatively, visit the installation page of a package from CRAN, go
to Downloads > Old sources >
<pkg> archive and find the appropriate URL pointing
to an older version to install it using base R. For example, to install
version 1.40 of package deSolve:
install.packages(
pkgs = "https://cran.r-project.org/src/contrib/Archive/deSolve/deSolve_1.40.tar.gz",
lib = .libPaths(), repos = NULL, dependencies = NA,
type = getOption("pkgType"), verbose = getOption("verbose"),
quiet = FALSE)Bioconductor
Older versions of packages from Bioconductor can be installed by
changing the value of argument version of
BiocManager::install() (e.g.,
BiocManager::install(pkgs = "deSolve", version = "3.22") to
indicate the version of deSolve included in Bioconductor
version 3.22) but that only works when using the version of R for that
specific version of Bioconductor, see the overview
of Bioconductor versions with the corresponding R version. Information
on these older packages can be found by visiting the appropriate version
of Bioconductor, e.g.,
https://bioconductor.org/packages/3.22/BiocViews.html.
Troubleshooting
Installing packages
If the warning
lib = <pkg> is not writeableor'lib' element <element from .libPaths()> is not a writable directoryoccurs, you probably forgot to run R (or RStudio) as administrator. Close it, right-click on the R (or RStudio) icon and selectRun as administratorto start it as administrator.-
If the question
Do you want to install from sources the packages which need compilation?is asked (in a new window), accompanied by the remarkThere are binary versions available but the source versions are laterwith an overview of the binary and source versions indicating if these need compilation, you can chooseYesto install the latest package versions by building them from source, or chooseNoto get slightly less up-to-date package versions but a faster installation.This question is only asked if you have installed Rtools. To install Rtools, see the section
Rtoolsin the vignette Installing R, Rtools and RStudio:vignette("install_r", package = "checkrpkgs"). If you want the latest version without using Rtools, you can try again a few days later: it usually takes a bit longer for the binaries (i.e., the package versions that do not have to be build from source) from CRAN and Bioconductor to be updated than for the source versions used by Rtools. The warning
package '<pkg>' is not available (for R version x.y.z)can have many reasons. First check the package name, which is case-sensitive. Then check possible other reasons mentioned in this stackoverflow answer.If installing packages fails, try with arguments
force = TRUEto re-install possibly broken dependencies and with argumentbuild_vignettes = FALSEto not install vignettes.
Using packages
If a package appears not to be installed when you want to use a function from it (e.g., you get the error
could not find function "<func>"), remember you need to runlibrary(<pkg>)to be able to use its functions.If
library(<pkg>)results in the errorthere is no package called '<pkg>', you have not installed the package, or it is not in any of the library paths returned by.libPaths(), which is where R looks for packages.-
To check that a package is installed and functional, use
library(<pkg)orrequireNamespace(<pkg>). These functions do not allow vectors as input, such that the following code has to be used to check multiple packages: If a package is not functional, re-install it using argument
force = TRUEto re-install possibly broken dependencies. You can also usetools::package_dependencies(packages = "<pkg>", recursive = TRUE)to check which dependencies it has andinstalled.packages(fields = "SystemRequirements")["<pkg>", "SystemRequirements"]to check which system requirements it has. On operating systems other than Windows,remotes::system_requirements(os = "<os>-<version>", package = <pkg>)can be used to get installation instructions for system requirements.If the warning
package <pkg> was built under R version 'x.y.z'occurs, you installed a binary package (i.e., not by building from source) that was prepared (‘compiled’) for an earlier version of R than the version of R you are currently using (rungetRversion()to see your current R version). The warning is issued because packages are not tested on versions of R that are older than the version they were built on. Therefore it is best to update R when installing packages.If errors occur when loading and attaching packages that require Java, make sure the 64-bit version of Java is installed on 64-bit PCs.
Information about packages
Information about packages can be obtained from the internet before the packages are installed, and from within R after the packages are installed.
Not-yet-installed packages
Available packages
utils::available.packages() and
tools::CRAN_package_db() give information about packages
available from CRAN;
utils::available.packages(repos = BiocManager::repositories())
gives information about packages available from Bioconductor,
and BiocManager::available() gives their names.
Documentation
The reference
manual is a PDF-file with all the help files of the standard and
recommended packages. The manuals and help pages of all packages from
CRAN can be searched online, or from within
R using utils::RSiteSearch(). In addition,
utils::help.search() can be used to search the help system
using fuzzy matching or regular expressions, which can be disabled by
setting argument agrep to FALSE to search
faster and return fewer results:
utils::help.search(..., agrep = FALSE).
Dependencies
For (not necessarily installed) packages from CRAN, use
tools::package_dependencies(packages = "<pkg>", recursive = TRUE)
to see dependencies (i.e., which packages are required by package
<pkg>) and
tools::dependsOnPkgs(pkgs = "<pkg>", recursive = TRUE)
to see reverse dependencies (i.e., which packages require package
<pkg>). NULL is returned for packages
that are not found, whereas character(0) is returned for
packages that do not have any dependencies. To see dependencies of
packages from other repositories (e.g., GitHub), use package pkgdepends:
library(pkgdepends)
prop <- pkgdepends::new_pkg_deps("<repos>/<pkg>")
prop$solve()
prop$get_solution()$data
prop$draw()Source code
The source code of base R packages can be obtained from GitHub (see the section Repositories below), and installation pages of packages on CRAN frequently contain links to GitHub pages where their source code can be viewed.
Already-installed packages
Available packages
The locations where R looks for installed packages can be obtained
with .libPaths(). The names of all installed packages can
be obtained with .packages(all.available = TRUE). The
location where a particular package is installed can be obtained with
find.package(package = "<pkg>", lib.loc = NULL, verbose = TRUE),
using verbose = TRUE to get a warning if a package is found
more than once.
Documentation
library() (without providing arguments
package or help) and
utils::installed.packages() give details on installed
packages. Argument fields of the
utils::installed.packages() can be used to specify
additional fields to extract from the package DESCRIPTION,
for example
utils::installed.packages(fields = c("Repository", "Additional_repositories", "URL", "GithubRepo", "GithubUsername", "SystemRequirements")).
The Repository and URL fields show the
repository from which a package was installed and are conveniently shown
by sessioninfo::session_info(), which also has the option
to show only information about selected packages and their
dependencies.
Information about a package and its functions is available from
within R after the package has been installed and attached (i.e.,
library(<pkg>) has been run):
- Arguments of a function:
args("<func>"). - Citation for a package:
utils::citation("<pkg>"), withutils::citation()to cite R itself. - Conflicts (i.e., if objects with the same name exist in two or more
places on the search path):
base::conflicts(where = search(), detail = TRUE). See also the sectionConflictsinhelp("conflictRules", package = "base")andconflicted::conflicts_prefer(<pkg>::<func>)from packageconflictedto declare preferences. - Functions, finding functions and other objects whose name contains a
certain string:
utils::apropos("<string>"). - Functions, overview of all functions in a package:
ls(getNamespace("<pkg>"), all.names = TRUE)returns a character vector with the function names (the defaultall.names = FALSEignores names that start with a dot because those are for internal use in packages);help(package = "<pkg>")gives an overview with links to their help-pages if there is a file<pkg>.Rin folder<pkg>\R. - Help page of a function:
help("<func>"); indicate the package to distinguish functions with the same name from different packages:help("<func>", package = "<pkg>"); use quotes around the name of a function that start with a symbol to get its help page:help("%in%"). - Installation path of a package (i.e., where is a package installed):
find.package(package = "<pkg>", lib.loc = NULL, verbose = TRUE). - Methods for a function: for a generic class:
utils::methods(class = "<class>"); for a generic function:utils::methods("<func>"); for S3-methods:attr(utils::methods(class = "<class>"), "info"); for S4-methods:methods::showMethods(classes = "<class>", where = getNamespace("<pkg>")). - Version of a package that is currently used:
utils::packageVersion("<pkg>"). - Vignettes of a package: show them in a browser through
utils::browseVignettes(package = "<pkg>"), or list them withutils::vignette(package = "<pkg>").
Which packages are used?
The function loadedNamespaces() shows which packages are
loaded. getAnywhere(<func>) shows in which package a
function is defined. To see which packages are used in a script, looking
for ::, :::, library,
require, and namespace (e.g.,
loadNamespace(), requireNamespace()) will
cover most cases. However, various packages have their own way to create
dependencies on packages, see the overview at pak::scan_deps().
To see which packages are mentioned in comments, also look for:
-
conductor: Bioconductor, Neuroconductor -
CRAN: CRAN -
forge: R-Forge -
Git: GitHub -
packageandlibraries -
rOpenSci: rOpenSci -
verse: R-multiverse, R-universe, tidyverse, etc
Getting the source code
Acknowledgements
Partly based on:
- Bryan J. 2015.
Accessing R Source. - Ligges U. 2006.
R help desk: accessing the sources. RNews 6(4):43-45. - A community answer from StackOverflow.
- The help page for
utils::methods().
Repositories
The source code of the base
R packages is available at CRAN and at the SVN-project. Searching
the source code of the development version is easiest using the GitHub
mirror of the SVN-project, see also the documentation on searching GitHub.
The source code of packages from CRAN can
be searched at METACRAN, an
unofficial CRAN mirror. Alternatively, download the
source file from section Downloads of the CRAN page. The
source files have been compressed into a tar file so you
have to extract the files (right-click on the downloaded file and choose
extract all).
The source code of packages from Bioconductor in the current and development-version is available here.
The source code of packages from GitHub can be viewed directly on GitHub,
or after downloading the code to your PC by clicking the green
Code button on the repository page (e.g.,
https://github.com/JesseAlderliesten/checkrpkgs), choosing
Download ZIP, and unzipping the downloaded file
(right-click on the file and choose extract all).
Basic method
The simplest way to get the source code of a function is to type the
name of the function, without the brackets. For
example, use sd to see what happens when using
sd() to calculate the standard deviation:
sd
#> function (x, na.rm = FALSE)
#> sqrt(var(if (is.vector(x) || is.factor(x)) x else as.double(x),
#> na.rm = na.rm))
#> <bytecode: 0x562d4ff26f40>
#> <environment: namespace:stats>Some special cases:
- To distinguish functions with the same name from different packages,
specify the package followed by two colons:
<pkg>::<func>. - For non-exported functions, specify the package followed by three
colons:
<pkg>:::<func>(using only two colons will result in the error'<func>' is not an exported object from 'namespace:<pkg>'; if that error appears when using three colons, you probably looked in the wrong package, usegetAnywhere(<func>)to check in which package<func>is defined). Non-exported functions should not be used in code because they might change. - For functions such as
%in%(seehelp("%in%")) that start with a symbol, use backticks (`) around the name:
`%in%`
#> function (x, table)
#> match(x, table, nomatch = 0L) > 0L
#> <bytecode: 0x562d4bbf3cf0>
#> <environment: namespace:base>getAnywhere
A more robust alternative to the basic
method outlined above is to use
getAnywhere("<func>"), which looks in more places and
finds non-exported functions without the need to specify in which
package a function is defined. Although the quotes around the function
name are only required when looking for the source code of functions
that start with a symbol (e.g., %in%), it is most robust to
always use them.
UseMethod
If getAnywhere("<func>") returns
UseMethod("<func>"), the function has different
methods for different object classes and is S3-generic.
First use methods("<func>") to get an overview of the
available methods; then use a particular method
"<method>" from that overview and use
getAnywhere("<method>") to get the source code of
that method. The advantage over simply using
"<method>" is that
getAnywhere("<method>") also works for functions that
are not exported, which is indicated in the overview of
methods(<func>) by an asterisk and the remark
Non-visible functions are asterisked.
For example, the output of getAnywhere("mean") contains
UseMethod("mean"), indicating that mean is an
S3-generic:
getAnywhere("mean")
#> A single object matching 'mean' was found
#> It was found in the following places
#> package:base
#> namespace:base
#> with value
#>
#> function (x, ...)
#> UseMethod("mean")
#> <bytecode: 0x562d4dee2c88>
#> <environment: namespace:base>First use methods("mean") to get an overview of the
available methods:
methods("mean")
#> [1] mean.Date mean.default mean.difftime mean.POSIXct mean.POSIXlt
#> [6] mean.quosure*
#> see '?methods' for accessing help and source codeThe output shows, among others, the methods mean.Date
and mean.default. You can use
getAnywhere("mean.Date") to see the source code of the
method mean used with objects of class
Date.
getAnywhere("mean.Date")
#> A single object matching 'mean.Date' was found
#> It was found in the following places
#> package:base
#> registered S3 method for mean from namespace base
#> namespace:base
#> with value
#>
#> function (x, ...)
#> .Date(mean(unclass(x), ...))
#> <bytecode: 0x562d4f8cfda8>
#> <environment: namespace:base>You can also use getAnywhere("mean.default") to see the
source code of the method mean used with objects of classes
not listed in the output of methods("mean"):
getAnywhere("mean.default")
#> A single object matching 'mean.default' was found
#> It was found in the following places
#> package:base
#> registered S3 method for mean from namespace base
#> namespace:base
#> with value
#>
#> function (x, trim = 0, na.rm = FALSE, ...)
#> {
#> if (!is.numeric(x) && !is.complex(x) && !is.logical(x)) {
#> warning("argument is not numeric or logical: returning NA")
#> return(NA_real_)
#> }
#> if (isTRUE(na.rm))
#> x <- x[!is.na(x)]
#> if (!is.numeric(trim) || length(trim) != 1L)
#> stop("'trim' must be numeric of length one")
#> n <- length(x)
#> if (trim > 0 && n) {
#> if (is.complex(x))
#> stop("trimmed means are not defined for complex data")
#> if (anyNA(x))
#> return(NA_real_)
#> if (trim >= 0.5)
#> return(stats::median(x, na.rm = FALSE))
#> lo <- floor(n * trim) + 1
#> hi <- n + 1 - lo
#> x <- sort.int(x, partial = unique(c(lo, hi)))[lo:hi]
#> }
#> .Internal(mean(x))
#> }
#> <bytecode: 0x562d4f8d31c8>
#> <environment: namespace:base>standardGeneric
If getAnywhere("<func>") returns
standardGeneric("<func>"), the function has different
S4-methods for different object classes (see
help("Introduction", package = "methods")). Use
showMethods("<func>") to get an overview of the
available methods in all attached packages, or use
<pkg>:::<func> to get an overview of the
available methods from package <pkg>. Finally,
provide the function name as argument f and the selected
method as a character vector to argument signature (see
also help("signature")) of function
getMethod() to get the source code of a particular method:
getMethod(f = "<func>", signature = c(target = "<class>", current = "<class>")).
The example below shows how to find the source code of method
cbind2() used by the Matrix package to combine
two matrices that both have the Matrix class as defined by
package Matrix.
# Need to attach and load package 'Matrix' for this example to work
if(requireNamespace("Matrix")) {
library(Matrix)
getAnywhere("cbind2")
}
#> Loading required namespace: Matrix
#> A single object matching 'cbind2' was found
#> It was found in the following places
#> package:Matrix
#> package:methods
#> namespace:methods
#> with value
#>
#> new("standardGeneric", .Data = function (x, y, ...)
#> standardGeneric("cbind2"), generic = "cbind2", package = "methods",
#> group = list(), valueClass = character(0), signature = c("x",
#> "y"), default = NULL, skeleton = (function (x, y, ...)
#> stop(gettextf("invalid call in method dispatch to '%s' (no default method)",
#> "cbind2"), domain = NA))(x, y, ...))
#> <bytecode: 0x562d4d89ede0>
#> <environment: 0x562d4c503af8>
#> attr(,"generic")
#> [1] "cbind2"
#> attr(,"generic")attr(,"package")
#> [1] "methods"
#> attr(,"package")
#> [1] "methods"
#> attr(,"group")
#> list()
#> attr(,"valueClass")
#> character(0)
#> attr(,"signature")
#> [1] "x" "y"
#> attr(,"default")
#> `\001NULL\001`
#> attr(,"skeleton")
#> (function (x, y, ...)
#> stop(gettextf("invalid call in method dispatch to '%s' (no default method)",
#> "cbind2"), domain = NA))(x, y, ...)
#> attr(,"class")
#> [1] "standardGeneric"
#> attr(,"class")attr(,"package")
#> [1] "methods"standardGeneric("cbind2") indicates that
cbind2() is an S4 function, so use
showMethods("cbind2") to get an overview of the different
methods:
if(requireNamespace("Matrix")) {
library(Matrix)
showMethods("cbind2")
}
#> Function: cbind2 (package methods)
#> x="ANY", y="ANY"
#> x="ANY", y="missing"
#> x="matrix", y="Matrix"
#> x="Matrix", y="matrix"
#> x="Matrix", y="Matrix"
#> x="Matrix", y="missing"
#> x="Matrix", y="NULL"
#> x="Matrix", y="vector"
#> x="NULL", y="Matrix"
#> x="vector", y="Matrix"Then choose one of the returned methods. For example, to get the
source code of cbind2 used with two matrices that both have
the Matrix class defined by package
Matrix:
if(requireNamespace("Matrix")) {
library(Matrix)
getMethod(f = "cbind2", signature = c(x = "Matrix", y = "Matrix"))
}
#> Method Definition:
#>
#> function (x, y, ...)
#> cbind.Matrix(x, y, deparse.level = 0L)
#> <bytecode: 0x562d4f729f30>
#> <environment: namespace:Matrix>
#>
#> Signatures:
#> x y
#> target "Matrix" "Matrix"
#> defined "Matrix" "Matrix".Internal or .Primitive
If getAnywhere("<func>") returns
.Internal or .Primitive, the function is
internal or primitive (see help(".internalGenerics") and
help(".Primitive()")). The source code of such functions
can be viewed at code repositories, or on
your PC if you have installed R from source using
Rtools (see the section Rtools in the vignette
Installing R, Rtools and RStudio:
vignette("install_r", package = "checkrpkgs")).
Locate the file src/main/names.c and look in the first
column (printname) for the name of the R function to find
the appropriate c-entry which is given in the second column of that
file. Then either search for that c-entry using the GitHub search, or
manually locate the c-file (the name of the file is the c-entry without
the prefix do_) in src/main to get the file
with the source code.
For example, getAnywhere("matrix") shows, among others,
the line.Internal(matrix(data, nrow, ncol, byrow, dimnames, missing(nrow), missing(ncol))).
The file src/main/names.c
has as entry with matrix in the first column:{"matrix", do_matrix, 0, 11, 7, {PP_FUNCALL, PREC_FN, 0}}.
Searching src/main for matrix gives file array.c
as one of the results. That file contains the source code of
matrix. Similarly, getAnywhere("log10") shows
function (x) .Primitive("log10"). The file src/main/names.c
has as entry with log10 in the first column:{"log10", do_log1arg, 10, 1, 1, {PP_FUNCALL, PREC_FN, 0}}.
Searching src/main for log1arg gives file arithmetic.c
as one of its results. That file contains the source code of
log10.
Sometimes an R function is defined in a file that defines multiple
functions and thus has a general name. Then the file with c-code will
have a similar general name. For example, the source code of
make.names() is defined in src/library/base/R/character.R
which, among others, contains the code
.Internal(make.names(names, allow_)), and the c-code for
do_makenames() is in file src/main/character.c.
.Call
If getAnywhere("<func>") returns code that
contains .Call(...), the function contains a call to C or
C++ code. Although the file src/<pkg>.h (e.g., src/methods.h
if code is from package methods) contains an overview of
the C or C++ code included in a package, your best bet for finding the
source code is searching the
relevant part of the GitHub repository (e.g.,
https://github.com/r-devel/r-svn/tree/main/src/library/methods/src
for code from package methods), or installing the package
from source (see the section Rtools in the vignette
Installing R, Rtools and RStudio:
vignette("install_r", package = "checkrpkgs")) and
searching in the src folder of the downloaded code.
Documentation and help
Installing and managing packages
- Documentation from the R-universe
- Instructions on installing Bioconductor packages
- Section
Add-on packagesin theR Installation and Administration manualmanual - Section Troubleshooting above
Package status
- Check results from Bioconductor.
Source code
- Bryan J. 2015.
Accessing R Source. - Ligges U. 2006.
R help desk: accessing the sources. RNews 6(4):43-45. - A community answer from StackOverflow.
- The help page for
utils::methods().
Miscellaneous
- The book
What They Forgot to Teach You About Rby J. Bryan, J. Hester, S. Pileggi, and E. D. Aja - Section
Documentation and helpin the vignette Installing R, Rtools and RStudio:vignette("install_r", package = "checkrpkgs") - Search engines specific for R: METACRAN, r-project, Rseek, R-universe