R creating packages
last modified November 19, 2026
A package is the unit that R uses to share code. It bundles functions, data
sets, documentation, and tests under a name, and it gives the functions a
namespace so that their names do not collide with other packages.
install.packages, library, and :: all
work with packages, and a folder with the right structure can be built,
installed, and checked with the tools that ship with R. This article creates a
small package called calc from an empty directory, documents it
with roxygen2, adds a data set and a test, defines an S3 method, and runs the
build, install, and check commands. The examples use R 4.5.2 and roxygen2
8.1.1.
The examples need the roxygen2 package, which is not part of base R. Install it
once with install.packages("roxygen2"); the
installing packages section of the
introduction explains the details.
The package directory
A source package is a directory whose name is the package name. R looks for a
DESCRIPTION file at the top, an R directory with the
source files, and a NAMESPACE file that lists the exported
objects. Documentation lives in man, data in data,
and tests in tests; those three directories are optional at the
start. The calc package begins with the minimum that can be
built.
R can generate this skeleton from a session with
package.skeleton("calc", list = c("mean_of", "spread")), which
creates the directory, the R files, the man pages, and a DESCRIPTION with
placeholder fields. The generated files still need editing, and writing them by
hand shows what each field is for. The package.skeleton function
is a convenient starting point, not a replacement for the metadata and
documentation work below.
calc/
├── DESCRIPTION
├── LICENSE
├── NAMESPACE
└── R/
└── stats.R
The R directory holds ordinary R files. Every file is sourced when
the package is installed, so the functions become part of the package
namespace. A function is not visible to a user until the namespace exports it,
which is the job of the NAMESPACE file. The file below defines two
small functions, mean_of for the arithmetic mean and
spread for the difference between the largest and smallest value.
mean_of <- function(x) {
mean(x)
}
spread <- function(x) {
diff(range(x))
}
The names are plain objects in the package namespace. mean and
range are found in the base and stats packages, which every R
session attaches. The functions do not need to be in separate files; a large
package usually groups related functions in several files, and the file names
do not affect the exported names. A file that defines an S3 method or a
replacement function follows the same pattern.
export(mean_of) export(spread)
export makes a name available to code that attaches the package
with library. Without these lines the functions would still exist
inside the namespace, but a user would have to reach them with
calc:::, the operator for internals. A package that imports
functions from another package adds importFrom lines, and a
package that defines S3 methods adds S3method lines. In the
roxygen2 workflow the whole file is generated, so it should not be edited by
hand once roxygen2 owns it.
The DESCRIPTION file
DESCRIPTION is a DCF file, a simple format of Field:
value lines. R and CRAN read the package name, version, authors,
license, and dependencies from it. The Authors@R field is R code
that builds a person object, with roles aut for an
author and cre for the creator, who is also the maintainer and
must have an email address. The Description field is a paragraph,
not a title, and each continuation line is indented.
Package: calc
Title: Small Calculation Helpers
Version: 0.1.0
Authors@R: person("Ada", "Lovelace", email = "ada@example.com",
role = c("aut", "cre"))
Description: A small package that demonstrates the package structure and the
build, install, and check workflow.
License: MIT + file LICENSE
Encoding: UTF-8
The package name may contain letters, numbers, and dots, must start with a
letter, and must not be a reserved word. The title is written in title case and
does not end with a period. The version usually has the form
major.minor.patch; a released package usually starts at 0.1.0 and
increments the patch for fixes. License: MIT + file LICENSE tells R
to look for a LICENSE file, which for the MIT template contains
the year and the copyright holder.
YEAR: 2026 COPYRIGHT HOLDER: Ada Lovelace
A package that uses data serialised by a recent R needs a dependency on the R
version that can read it. The built package in this article adds
Depends: R (>= 3.5.0) for that reason, and it adds
LazyData: true when the data directory appears, so that data sets
can be used without an explicit data() call. Both fields are
ordinary lines in DESCRIPTION. A package with compiled code also
lists LinkingTo and SystemRequirements here.
Building and installing
R CMD build turns the source directory into a tarball with the
package name and version in the file name. R CMD INSTALL installs
the tarball into a library, and .libPaths adds that library to the
places where R looks for packages. A local library keeps the tutorial package
away from the system installation, and it does not need administrator rights.
The script below performs the three steps and calls the function.
#!/bin/sh
set -e
mkdir -p lib
R CMD build calc
R CMD INSTALL --library=lib calc_0.1.0.tar.gz
Rscript -e '.libPaths("lib"); library(calc); cat("mean:", mean_of(c(2, 4, 6)), "\n")'
set -e stops the script at the first command that fails, so a
broken build does not continue to an install of an old tarball.
R CMD build reports the checks it performs on the metadata and
writes calc_0.1.0.tar.gz. The install step reports each stage,
including the byte compilation of the R code and the installation of help
indices. The final line prints four, the mean of 2, 4, and 6. The message
No man pages found is expected, because the package has no
documentation yet.
$ sh build.sh * checking for file ‘calc/DESCRIPTION’ ... OK * preparing ‘calc’: * checking DESCRIPTION meta-information ... OK * checking for LF line-endings in source and make files and shell scripts * checking for empty or unneeded directories * building ‘calc_0.1.0.tar.gz’ * installing *source* package ‘calc’ ... ** this is package ‘calc’ version ‘0.1.0’ ** using staged installation ** R ** byte-compile and prepare package for lazy loading ** help No man pages found in package ‘calc’ *** installing help indices ** building package indices ** testing if installed package can be loaded from temporary location ** testing if installed package can be loaded from final location ** testing if installed package keeps a record of temporary installation path * DONE (calc) mean: 4
Documenting with roxygen2
roxygen2 reads special comments above a function and writes the Rd help page
and the NAMESPACE entries. A comment line that starts with #'
belongs to the object below it. The tags start with @:
@param describes an argument, @return describes the
value, @export adds the name to NAMESPACE, and
@examples adds a runnable example. The prose between the tags
becomes the description.
#' Arithmetic mean
#'
#' Computes the arithmetic mean of a numeric vector.
#'
#' @param x A numeric vector.
#' @return A single number.
#' @export
#' @examples
#' mean_of(c(2, 4, 6))
mean_of <- function(x) {
mean(x)
}
#' Range of a vector
#'
#' Computes the difference between the largest and the smallest value.
#'
#' @param x A numeric vector.
#' @return A single number.
#' @export
#' @examples
#' spread(c(2, 9, 4))
spread <- function(x) {
diff(range(x))
}
The hand-written NAMESPACE from the first section is deleted before
the first roxygen2 run, because roxygen2 refuses to overwrite a file that it
did not generate. After that, roxygenise owns both the NAMESPACE
and the files under man. The command reports each file it writes;
the two function pages and the namespace are created from the comments alone.
The Roxygen: list(markdown = TRUE) line in
DESCRIPTION enables markdown in the comments, so backticks and
lists can be used in the description. roxygen2 also records the version it
used in a Config/roxygen2/version field, so a later run can warn
when the files were generated by a different version.
$ Rscript -e 'roxygen2::roxygenise("calc")'
ℹ Loading calc
Writing 'NAMESPACE'
Writing 'mean_of.Rd'
Writing 'spread.Rd'
The generated help page
The generated file is readable Rd, the markup that R uses for help pages. The
\name and \alias entries connect the page to the
function, so ?mean_of finds it. \title is the short
heading, \usage shows the call, and \arguments
documents each parameter. \value, \description, and
\examples hold the remaining sections. The header warns that the
file is generated and that edits belong in the R source.
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/stats.R
\name{mean_of}
\alias{mean_of}
\title{Arithmetic mean}
\usage{
mean_of(x)
}
\arguments{
\item{x}{A numeric vector.}
}
\value{
A single number.
}
\description{
Computes the arithmetic mean of a numeric vector.
}
\examples{
mean_of(c(2, 4, 6))
}
The example is not just documentation: R CMD check runs it and
reports a failure if it errors. That makes the examples a small test suite for
the public interface. The \usage section must match the actual
argument list, and check compares them; a missing parameter in the
documentation is reported as a mismatch. Once the page is generated, the
installed package serves it through the help system.
Checking the package
R CMD check is the tool that CRAN runs before accepting a package.
It installs the tarball in a temporary library, loads and unloads it, checks
the namespace and the documentation, compares the usage sections with the
function definitions, runs the examples, and inspects the package for common
problems. The --no-manual option skips the PDF manual, which needs
a LaTeX installation. A clean package ends with Status: OK.
R CMD check --no-manual calc_0.1.0.tar.gz
The output below is the full run for the documented package. Every check line
ends in OK, including the checks for the namespace, the R files, the Rd
files, and the examples. The log is also written to
calc.Rcheck/00check.log, which is the file to read when a check
fails. A warning or a note does not stop the build, but it should be read
before the package is shared.
$ R CMD check --no-manual calc_0.1.0.tar.gz
* using log directory ‘/home/ada/projects/calc.Rcheck’
* using R version 4.5.2 (2025-10-31)
* using platform: x86_64-pc-linux-gnu
* R was compiled by
gcc (Debian 15.2.0-7) 15.2.0
GNU Fortran (Debian 15.2.0-7) 15.2.0
* running under: Debian GNU/Linux forky/sid
* using session charset: UTF-8
* using option ‘--no-manual’
* checking for file ‘calc/DESCRIPTION’ ... OK
* this is package ‘calc’ version ‘0.1.0’
* package encoding: UTF-8
* checking package namespace information ... OK
* checking package dependencies ... OK
* checking if this is a source package ... OK
* checking if there is a namespace ... OK
* checking for .dll and .exe files ... OK
* checking for hidden files and directories ... OK
* checking for portable file names ... OK
* checking for sufficient/correct file permissions ... OK
* checking whether package ‘calc’ can be installed ... OK
* checking installed package size ... OK
* checking package directory ... OK
* checking DESCRIPTION meta-information ... OK
* checking top-level files ... OK
* checking for left-over files ... OK
* checking index information ... OK
* checking package subdirectories ... OK
* checking code files for non-ASCII characters ... OK
* checking R files for syntax errors ... OK
* checking whether the package can be loaded ... OK
* checking whether the package can be loaded with stated dependencies ... OK
* checking whether the package can be unloaded cleanly ... OK
* checking whether the namespace can be loaded with stated dependencies ... OK
* checking whether the namespace can be unloaded cleanly ... OK
* checking loading without being on the library search path ... OK
* checking dependencies in R code ... OK
* checking S3 generic/method consistency ... OK
* checking replacement functions ... OK
* checking foreign function calls ... OK
* checking R code for possible problems ... OK
* checking Rd files ... OK
* checking Rd metadata ... OK
* checking Rd cross-references ... OK
* checking for missing documentation entries ... OK
* checking for code/documentation mismatches ... OK
* checking Rd \usage sections ... OK
* checking Rd contents ... OK
* checking for unstated dependencies in examples ... OK
* checking examples ... OK
* DONE
Status: OK
Adding data
A data set is stored as an .rda file in the data
directory. The file is created once, by a script that keeps the source of the
data reproducible; the script itself is usually kept outside the package, in a
data-raw directory, so that rebuilding the package does not rerun
it. save with compress = "xz" produces a small file,
and the object name inside the file is the name that users will load.
measurements <- data.frame(
station = c("A", "B", "C"),
temp = c(12.5, 10.0, 8.5)
)
dir.create("calc/data", showWarnings = FALSE)
save(measurements, file = "calc/data/measurements.rda", compress = "xz")
cat("saved", nrow(measurements), "rows to calc/data/measurements.rda\n")
The data needs a help page like a function. roxygen2 marks a data set with
@format and @source, and the object name is written as
a string after the comment block. The \describe list explains each
variable, and the @format line states the dimensions. The page is
generated into man/measurements.Rd with
\docType{data}, so ?measurements works after the
package is installed.
#' Temperature measurements
#'
#' Temperatures recorded at three weather stations.
#'
#' @format A data frame with 3 rows and 2 variables:
#' \describe{
#' \item{station}{Station name.}
#' \item{temp}{Temperature in degrees Celsius.}
#' }
#' @source Simulated for the tutorial.
"measurements"
The script below creates the file, regenerates the documentation, installs the
package from the source directory, and loads the data. Installing from
calc rather than from the tarball is convenient during
development, because it picks up the new data directory without a
separate build. The LazyData: true line in
DESCRIPTION makes measurements available after
library(calc); data(measurements) loads it explicitly
and also works.
#!/bin/sh
set -e
Rscript make_data.R
Rscript -e 'roxygen2::roxygenise("calc")'
R CMD INSTALL --library=lib calc
Rscript -e '.libPaths("lib"); library(calc); data(measurements); print(measurements); cat("rows:", nrow(measurements), "\n")'
The install reports a new ** data stage, where R moves the data
sets into a lazy-load database. The printed frame has the three stations and
their temperatures, and nrow confirms the row count. The file
measurements.rda is not read directly by user code; R finds it
through the package metadata. A data set that should be available without
LazyData can still be loaded with data(), but the
lazy option is the usual choice for small tutorial data.
$ sh data.sh saved 3 rows to calc/data/measurements.rda ℹ Loading calc Writing 'measurements.Rd' * installing *source* package ‘calc’ ... ** this is package ‘calc’ version ‘0.1.0’ ** using staged installation ** R ** data *** moving datasets to lazyload DB ** byte-compile and prepare package for lazy loading ** help *** installing help indices ** building package indices ** testing if installed package can be loaded from temporary location ** testing if installed package can be loaded from final location ** testing if installed package keeps a record of temporary installation path * DONE (calc) station temp 1 A 12.5 2 B 10.0 3 C 8.5 rows: 3
Adding tests
R CMD check runs every .R file in the
tests directory and fails the check if a file stops with an error.
Base R therefore needs no test framework for a small package:
stopifnot raises an error when its argument is not true, and a
final cat reports success. The test file lives in the source
package, not in the installed library, and it runs in a fresh R session during
the check.
library(calc)
stopifnot(identical(mean_of(c(2, 4, 6)), 4))
stopifnot(identical(spread(c(2, 9, 4)), 7))
stopifnot(nrow(measurements) == 3)
cat("all tests passed\n")
The first two assertions compare exact values; identical also
checks the type, so a result of 4L would fail against the double
4. The third assertion uses the lazy data set, which confirms that
the data directory is installed correctly. Running the file against the local
library prints the success line. During R CMD check, the same file
runs in the temporary library and a failure would appear under
* checking tests ....
$ Rscript -e '.libPaths("lib"); source("calc/tests/basic.R")'
all tests passed
Adding an S3 method
An S3 class is an attribute on an ordinary object, and a method is a function
whose name combines the generic and the class, such as
print.calc. The constructor builds a list and sets the class
attribute; the print method receives the object as its first argument and
returns it invisibly, so that a call at the top level does not print the object
twice. The @export tag on print.calc makes roxygen2
write an S3method(print,calc) line, which registers the method
with the generic.
#' Create a calculation object
#'
#' @param values A numeric vector.
#' @param label A short description.
#' @return An object of class `calc`.
#' @export
new_calc <- function(values, label = "calculation") {
structure(list(values = values, label = label), class = "calc")
}
#' Print a calculation object
#'
#' @param x A `calc` object.
#' @param ... Ignored.
#' @return `x`, invisibly.
#' @export
print.calc <- function(x, ...) {
cat(x$label, ": ", length(x$values), " values, mean ",
format(mean_of(x$values)), "\n", sep = "")
invisible(x)
}
The script regenerates the documentation, installs the package, creates an
object, and prints it. roxygen2 writes the two new help pages, refreshes the
data page, and adds the method to NAMESPACE. The print output is one line: the
label, the number of values, and their mean. class(x) is
"calc", which is the class that dispatch uses to find
print.calc. A second class, such as c("scores", "calc"),
would let a more specific method run first and fall back to this one.
#!/bin/sh
set -e
Rscript -e 'roxygen2::roxygenise("calc")'
R CMD INSTALL --library=lib calc
Rscript -e '.libPaths("lib"); library(calc); x <- new_calc(c(2, 4, 6), "scores"); print(x); cat("class:", class(x), "\n")'
The NAMESPACE now contains the generated header, the print method, and the
exports for the constructor and the two original functions. The installed
package dispatches print(x) to print.calc without any
explicit call to the method. The trailing cat shows the class
vector; the method itself prints the formatted line and returns the object
invisibly.
$ sh use_class.sh ℹ Loading calc Writing 'NAMESPACE' Writing 'new_calc.Rd' Writing 'print.calc.Rd' Writing 'measurements.Rd' * installing *source* package ‘calc’ ... ** this is package ‘calc’ version ‘0.1.0’ ** using staged installation ** R ** data *** moving datasets to lazyload DB ** byte-compile and prepare package for lazy loading ** help *** installing help indices ** building package indices ** testing if installed package can be loaded from temporary location ** testing if installed package can be loaded from final location ** testing if installed package keeps a record of temporary installation path * DONE (calc) scores: 3 values, mean 4 class: calc
The complete workflow
The final script runs the whole sequence from a clean checkout: regenerate the
documentation, build the tarball, install it into the local library, run the
check, and print the last lines of the check log. The check output is
redirected to check.log because it is long; the last three lines
contain the completion marker and the status. The package now has functions,
help pages, data, tests, and an S3 method, and the check covers all of them.
#!/bin/sh
set -e
mkdir -p lib
Rscript -e 'roxygen2::roxygenise("calc")'
R CMD build calc
R CMD INSTALL --library=lib calc_0.1.0.tar.gz
R CMD check --no-manual calc_0.1.0.tar.gz > check.log 2>&1
tail -n 3 check.log
The run ends with Status: OK, which means the package passed every
check that R could perform without the PDF manual. The build step checks the
metadata, the install step reports the data stage, and the check runs the
example from the help page and the assertion file from the tests directory. The
log remains on disk for inspection. A warning or a note would appear above the
status and should be fixed before the package is submitted to CRAN.
$ sh build.sh ℹ Loading calc * checking for file ‘calc/DESCRIPTION’ ... OK * preparing ‘calc’: * checking DESCRIPTION meta-information ... OK * checking for LF line-endings in source and make files and shell scripts * checking for empty or unneeded directories * building ‘calc_0.1.0.tar.gz’ * installing *source* package ‘calc’ ... ** this is package ‘calc’ version ‘0.1.0’ ** using staged installation ** R ** data *** moving datasets to lazyload DB ** byte-compile and prepare package for lazy loading ** help *** installing help indices ** building package indices ** testing if installed package can be loaded from temporary location ** testing if installed package can be loaded from final location ** testing if installed package keeps a record of temporary installation path * DONE (calc) Status: OK
Next steps
The packages article explains how installed
packages are attached, detached, and found, and the
S3 classes article covers the dispatch rules behind
print.calc in more detail. The
error handling article shows how to signal
useful conditions from the functions that a package exports, and the
debugging article shows how to find a failure
inside a package that is already installed. The
data I/O article covers the file formats that the
data directory does not handle.
Source
R Packages: organize, test, document, and share your code
roxygen2 package documentation
In this article we have created a package directory with a
DESCRIPTION, a NAMESPACE, and an R source file, then
built and installed it with R CMD build and
R CMD INSTALL. roxygen2 generated the help pages and the
namespace, and R CMD check verified the documentation, the
examples, the data, and the tests. A data set and an S3 print method extended
the package, and the final script ran the complete workflow from documentation
to a clean check status. The packages article
covers using packages that other people have published, and the
debugging article shows how to find a failure
inside one of them.
Author
List all R Language tutorials.