install.packages("DoseFinding")
library(DoseFinding)
help(package = "DoseFinding")Overview
This session introduced the basics of R packages: what they are, where they live, how to install and load them, and how to manage common issues such as library paths, dependencies, package masking, archived packages, GitHub installs, and reproducible project libraries with renv.
What is a package?
An R package is a bundle of reusable code, documentation, metadata, tests, and sometimes data.
Packages help us:
- Reuse functions without copying code between projects
- Share statistical methods and workflows
- Document how functions should be used
- Track versions and dependencies
- Make analysis more reproducible
Package example
DoseFinding is a useful example of a package from the clinical trials space. On CRAN, it is described as a package for planning and analysing dose-finding experiments, with a focus on pharmaceutical Phase II clinical trials.
Package pages are useful because they show the package version, maintainer, dependencies, documentation, vignettes, CRAN checks, and links to source code or issue trackers.
Where do packages live?
R looks for installed packages in library folders.
# Show all library paths searched by R
.libPaths()The search order matters. R checks the first path first, then moves through the remaining paths.
Typical library locations include:
- User library: packages installed for your user account
- System library: packages installed for everyone on the machine
- Project library: packages installed for a specific project, often through
renv
Installing into a user or project library is usually safer than installing directly into C:/Program Files, where write access may be restricted.
Inspecting installed packages
Start by looking at where R searches for packages and which packages are already installed.
# Show the current library paths where R looks for packages
.libPaths()
# List all installed packages (data frame of package metadata)
installed.packages()Changing and resetting library paths
Changing .libPaths() can be useful for demonstrations, testing, and understanding where packages are being installed from. It is best to save the original paths first so they can be restored.
# Save the current library search paths so we can restore them later
old_libpaths <- .libPaths()
# Temporarily set the library path to a temp folder (not recommended long-term)
.libPaths(tempdir())
# Change library path to the current working directory
.libPaths(getwd())
# Restore the original library paths
.libPaths(old_libpaths)
# Prepend a custom folder to the library paths
.libPaths(c("C:/Users/Martin.Brown1/Desktop/OldCBTI/WorkBTI/RDemo/Test Folder",
old_libpaths))Installing packages into different locations
install.packages() downloads and installs packages from CRAN or a CRAN mirror. By default, R installs into the first writable library in .libPaths().
# Install DoseFinding into the *first* library in .libPaths()
install.packages("DoseFinding")
# Install 'stringr' into a specific library folder, using a custom CRAN mirror,
# and without installing dependencies
install.packages(
"stringr",
lib = "C:/Users/Martin.Brown1/Desktop/OldCBTI/WorkBTI/RDemo/Test Folder2",
repos = "https://cran.ma.imperial.ac.uk/",
dependencies = FALSE
)
# Overwrite library paths to look only in Program Files
# (R likely has no write access here)
.libPaths("C:/Program Files")
# Install a package from a source tarball (older version from CRAN Archive)
install.packages(
"https://cran.r-project.org/src/contrib/Archive/DoseFinding/DoseFinding_1.3-1.tar.gz",
repos = NULL, type = "source"
)
# Remove a previously installed package
remove.packages("DoseFinding")Demonstrating function masking and namespaces
Installing a package puts it on your machine. Loading a package attaches it to your R session.
words <- c("First","Second","Third")
# Calling str_length() *before* loading stringr - will fail unless stringr loaded
str_length(words)
library(stringr)
# Now str_length() works because stringr is attached
str_length(words)
# Detach the package completely
detach("package:stringr", unload = TRUE)
# Using the function explicitly via namespace, without attaching the package
stringr::str_length(words)The package::function() style is especially useful in scripts, teaching material, and regulated work because it makes the source of the function explicit.
Detaching packages
During demonstrations, you may want to detach a package after loading it.
detach("package:stringr", unload = TRUE)In day-to-day analysis, restarting R is often the cleanest way to reset the session.
The global environment
Installed packages do not put every function into the global environment.
When you run:
library(readr)R attaches the package so that exported functions such as read_csv() are available by name.
Objects you create yourself, such as data frames and variables, live in the global environment unless they are created inside a function or another environment.
Function masking
Masking happens when two attached packages provide functions with the same name. The function from the package earlier on the search path is used first.
filter() is a common example because both dplyr and stats provide a function called filter().
install.packages("dplyr")
library(dplyr)
View(iris)
# dplyr::filter() filters rows
filter(iris, Sepal.Length > 7)
# Detach stats (usually not needed - just for demonstration)
detach("package:stats", unload = TRUE)
# Re-load stats
library(stats)
# Now filter() may refer to stats::filter (time-series filter!), not dplyr
filter(iris, Sepal.Length > 7) # likely error or unexpected result
# Help for filter will show the stats version
?filter
# Use the fully qualified dplyr function
dplyr::filter(iris, Sepal.Length > 7)Use explicit namespaces when there is any ambiguity.
Reading a CSV with readr
readr is a tidyverse package for reading rectangular text data such as CSV files.
# Point the library path to a custom folder
.libPaths("C:/Users/Martin.Brown1/Desktop/OldCBTI/WorkBTI/RDemo/Test Folder3")
# Install readr into that folder
install.packages("readr")
library(readr)
?read_csv
# Read a CSV file using readr
MAI <- read_csv(
file = "C:/Users/Martin.Brown1/Desktop/OldCBTI/WorkBTI/RDemo/MAI.csv"
)Checking versions and session information
When sharing code or debugging package problems, version information is often important.
packageVersion("ggplot2")
sessionInfo()sessionInfo() records the R version, operating system, attached packages, and loaded namespaces.
Installing from GitHub
Not every package version is installed from CRAN. Some package releases are installed from GitHub.
One option is remotes.
install.packages("remotes") # install once
# Install a specific tagged GitHub release
remotes::install_github(
"insightsengineering/teal.reporter",
ref = "v0.5.0"
)Another option is pak.
install.packages("pak") # install once
# Install the same tagged release, using pak's syntax
pak::pkg_install("github::insightsengineering/teal.reporter@v0.5.0")Pinning a tag or commit helps make the install more reproducible than installing whatever happens to be on the default branch.
Installing archived packages
Sometimes packages are archived on CRAN. Archived packages are no longer active on the main CRAN package list, but older source versions may still be available from the CRAN archive.
For example, if an archived package depends on other packages, install those dependencies first.
install.packages(c("mvtnorm", "clinfun"), dependencies = FALSE)
package_url <- "https://cran.r-project.org/src/contrib/Archive/ph2hetero/ph2hetero_1.0.2.tar.gz"
install.packages(package_url, repos = NULL, type = "source")
library(ph2hetero)
help(package = "ph2hetero")Installing from source may require additional tools, especially on Windows. Archived packages should be used with care because they may no longer pass current CRAN checks or current R versions.
Reproducible libraries with renv
renv helps projects use their own package library and record exact package versions in a lockfile.
A minimal workflow is:
# Set the library path to a clean folder for the renv demo
.libPaths("C:/Users/Martin.Brown1/Desktop/OldCBTI/WorkBTI/RDemo/Test Folder3")
install.packages("renv")
# Initialize renv WITHOUT scanning the project for dependencies
renv::init(bare = TRUE)
# Install a package inside the renv environment
install.packages("stringr") # or any package you like
# Snapshot the exact state of the renv library to renv.lock
renv::snapshot()
# Show dependencies that renv thinks are in the project
renv::dependencies()The lockfile can then be used later to restore the package environment.
Packages recap
Key points from the session:
- Packages are reusable, documented bundles of R code
- R searches library paths in order
- User and project libraries are usually safer than system locations
install.packages()installs packages;library()attaches them- CRAN mirrors and dependencies matter when installing packages
- Use
package::function()when function names are ambiguous detach()can remove a package from the search path, but restarting R is often cleaner- Package versions and
sessionInfo()help with troubleshooting - GitHub installs should be pinned to a tag or commit when reproducibility matters
renvcan record and restore project-specific package versions