Create an R Package
An R package connects a set of functions to help pages, dependencies, and tests. Another project can install it and call an exported function without sourcing your analysis scripts in a particular order.
This lesson builds genetools, a small package that calculates the GC fraction
of one DNA sequence. It brings together the roxygen2 tags from
Documentation and style and the
unit tests from Testing and assertions.
The complete project download
includes the source, tests, and generated help files.
Create the package directory
Section titled “Create the package directory”Create a directory named genetools. Save the files below under their named
paths, and run the shell commands from that directory in Bash. The examples
require R with roxygen2 and testthat available in its library.
This example uses R 4.6.1, roxygen2 8.1.0, and testthat 3.3.2.
The package management lesson explains
package installation and project libraries.
genetools/ DESCRIPTION LICENSE README.md .Rbuildignore R/gc_fraction.R tests/testthat.R tests/testthat/test_gc_fraction.R scripts/document.R scripts/test_local.R scripts/check_install.R NAMESPACE man/GcFraction.RdYou write the source under R/. roxygen2 creates NAMESPACE and
man/GcFraction.Rd later, so leave those two files absent at this point.
The scripts/ directory holds development commands and the installation check;
it is excluded from the package archive.
The package name starts with a letter and uses letters only. R package names
cannot contain underscores, although source filenames can. The exported
function uses BigCamelCase, following this site’s Google R convention.
Describe the package and its dependencies
Section titled “Describe the package and its dependencies”Save the following as DESCRIPTION. The indented lines continue the field
above them. Replace the tutorial maintainer details before distributing your
own package.
Package: genetoolsTitle: Calculate a GC Fraction for a DNA SequenceVersion: 0.1.0Authors@R: person("Tutorial", "Maintainer", email = "maintainer@example.org", role = c("aut", "cre"))Description: Calculate the fraction of guanine and cytosine bases in a single DNA sequence. Accept uppercase and lowercase canonical bases and reject empty sequences, missing values, and ambiguous bases.License: MIT + file LICENSEEncoding: UTF-8Suggests: testthat (>= 3.0.0)Config/testthat/edition: 3Roxygen: list(markdown = TRUE)The example function uses base R, so it has no Imports field. testthat
belongs in Suggests because it runs tests rather than the public calculation.
roxygen2 is a development tool: an installer reads the generated help files
without running roxygen2.
For a future runtime dependency, declare the package in Imports and call
its function with package::function(). If you deliberately import an
unqualified name, add the matching @importFrom tag as well.
The namespace operator alone does not declare the dependency in DESCRIPTION.
A renv.lock file records a development environment; it does not replace
these package requirements.
Save the MIT license metadata as LICENSE.
YEAR: 2026COPYRIGHT HOLDER: Bench to Insights contributorsR combines this file with its MIT license template. For your own package, use the appropriate copyright holder and license. The example maintainer address is a placeholder, not a contact for submissions.
Save the package description as README.md.
# genetools
The package calculates the GC fraction of one DNA sequence.It accepts uppercase or lowercase A, C, G, and T.It rejects empty input, missing values, whitespace, gaps, and ambiguous bases.The result is a fraction between zero and one.
Run `Rscript scripts/document.R` to generate the help page and exports.Run `Rscript scripts/test_local.R` to execute the unit tests.Write a function with roxygen2 documentation
Section titled “Write a function with roxygen2 documentation”Save this code as R/gc_fraction.R.
#' Calculate the GC fraction of a DNA sequence.#'#' @param sequence One nonmissing, nonempty character string containing#' A, C, G, and T. Lowercase letters are accepted.#' @return One numeric value between zero and one.#' @details Whitespace, gaps, and ambiguous bases such as N cause an error.#' The function does not remove characters from the denominator.#' @examples#' GcFraction("ACGT")#' GcFraction("acgt")#' @exportGcFraction <- function(sequence) { if (!is.character(sequence) || length(sequence) != 1L || is.na(sequence) || !nzchar(sequence)) { stop("sequence must be one nonmissing, nonempty string", call. = FALSE) } normalized_sequence <- toupper(sequence) if (grepl("[^ACGT]", normalized_sequence)) { stop("sequence must contain only A, C, G, and T", call. = FALSE) } bases <- strsplit(normalized_sequence, "", fixed = TRUE)[[1]] return(mean(bases %in% c("G", "C")))}The #' prefix distinguishes a roxygen block from an ordinary comment.
The tags describe the function and determine its export.
| Tag | Effect |
|---|---|
@param |
It documents an argument and its accepted values. |
@return |
It states the result type and meaning. |
@details |
It explains the input policy that affects the calculation. |
@examples |
It supplies executable examples for the help page. |
@export |
It makes the function available through genetools::GcFraction. |
The input checks reject a vector of sequences, a factor, and a missing value
before calculation. N is rejected rather than removed. Removing it would
change which bases contribute to the fraction, so accepting ambiguous bases
would require another documented rule.
Generate the help page and namespace
Section titled “Generate the help page and namespace”Save the following as scripts/document.R.
roxygen2::roxygenise(".", roclets = c("rd", "namespace"))cat(readLines("NAMESPACE"), sep = "\n")Run the saved script from the package root.
Rscript scripts/document.R# Generated by roxygen2: do not edit by hand
export(GcFraction)roxygen2 writes man/GcFraction.Rd and an export entry in NAMESPACE.
It also records its version in DESCRIPTION as Config/roxygen2/version.
devtools::document() provides another interface to the same document process.
Commit the generated help and namespace with the R source. An installer needs those files even if roxygen2 is absent. Edit the roxygen block when the function changes, then run the script again instead of editing generated files.
Connect testthat to the package
Section titled “Connect testthat to the package”The test entry file tells R CMD check to run the package suite. Save it as
tests/testthat.R.
library(testthat)library(genetools)
test_check("genetools")Save the linked notice as inst/licenses/testthat_3.3.2.txt so it travels
with the adapted entry file. The complete project download includes it.
Save the actual tests as tests/testthat/test_gc_fraction.R. testthat finds
files whose names begin with test.
testthat::test_that("GcFraction returns known fractions", { testthat::expect_equal(genetools::GcFraction("A"), 0) testthat::expect_equal(genetools::GcFraction("G"), 1) testthat::expect_equal(genetools::GcFraction("ATAT"), 0) testthat::expect_equal(genetools::GcFraction("GCGC"), 1) testthat::expect_equal(genetools::GcFraction("ACGT"), 0.5) testthat::expect_equal(genetools::GcFraction("acgt"), 0.5)})
testthat::test_that("GcFraction rejects unsupported characters", { for (sequence in c("AUGC", "ACGN", "AC GT", "ACGT\n", "A-C")) { testthat::expect_error( genetools::GcFraction(sequence), "only A, C, G, and T" ) }})
testthat::test_that("GcFraction requires one nonmissing string", { invalid_inputs <- list( "", NULL, 42, NA_character_, character(), c("A", "C"), factor("A") ) for (sequence in invalid_inputs) { testthat::expect_error( genetools::GcFraction(sequence), "one nonmissing, nonempty string" ) }})
testthat::test_that("repetition preserves the GC fraction", { sequence <- "AACGT" testthat::expect_equal( genetools::GcFraction(strrep(sequence, 7)), genetools::GcFraction(sequence) ) testthat::expect_identical(sequence, "AACGT")})The tests use genetools::GcFraction to exercise the exported name.
Known fractions check the scale, invalid inputs check the error policy, and
repetition checks a property that should hold for any accepted sequence.
Save the development command as scripts/test_local.R.
testthat::test_local( ".", reporter = testthat::SummaryReporter$new(show_praise = FALSE), stop_on_failure = TRUE)Rscript scripts/test_local.Rgc_fraction: ....................
══ DONE ════════════════════════════════════════════════════════════════════════test_local() loads the source package for development. It does not prove
that an archive contains the same source, help files, and tests. The next
commands check the archive that another person can install.
Build and check the source archive
Section titled “Build and check the source archive”Save the following patterns as .Rbuildignore. Each line is a regular
expression for paths to exclude from the source archive.
^scripts$^artifacts$^consumer$^genetools_[0-9].*\.tar\.gz$^.*\.Rproj$^\.Rproj\.user$The archive retains R/, tests/, man/, DESCRIPTION, NAMESPACE, and
the license. It excludes the development scripts and generated artifacts.
Keep the artifacts/ and consumer/ directories out of Git too.
mkdir -p artifactsR CMD build --no-build-vignettes --no-manual .mv genetools_0.1.0.tar.gz artifacts/cd artifactsR CMD check --no-manual --no-vignettes genetools_0.1.0.tar.gzRead artifacts/genetools.Rcheck/00check.log. A successful check ends with
Status: OK. Investigate errors, warnings, and notes before sharing the
archive. A zero command exit status alone does not establish that the check
has no warnings.
The check installs the archive, examines metadata and namespace use, runs the
help examples, and executes tests/testthat.R. The flags omit PDF manual and
vignette builds; they do not omit the function examples or unit tests. This
package contains no vignette. A package that adds one needs a separate vignette
build before release.
Install and test outside the source directory
Section titled “Install and test outside the source directory”Save this script as scripts/check_install.R. Its library path assertion
confirms that the import comes from the consumer’s private library.
installed_path <- normalizePath(find.package("genetools"))expected_path <- normalizePath(file.path("library", "genetools"))stopifnot(identical(installed_path, expected_path))stopifnot(as.character(utils::packageVersion("genetools")) == "0.1.0")stopifnot(length(utils::help("GcFraction", package = "genetools")) == 1L)stopifnot(identical(genetools::GcFraction("ACGT"), 0.5))installed_version <- as.character(utils::packageVersion("genetools"))cat("Installed version:", installed_version, "\n")cat("GC fraction:", genetools::GcFraction("ACGT"), "\n")test_path <- system.file("tests", "testthat", package = "genetools")stopifnot(nzchar(test_path), length(list.files(test_path, "^test")) > 0L)testthat::test_package( "genetools", reporter = testthat::SummaryReporter$new(show_praise = FALSE), stop_on_failure = TRUE)The previous shell block left you in artifacts/. Return to the package
root, create a private library, and install the source archive with its tests.
cd ..mkdir -p consumer/libraryR CMD INSTALL --install-tests --library=consumer/library \ artifacts/genetools_0.1.0.tar.gzcp scripts/check_install.R consumer/check_install.Rcd consumerR_LIBS_USER="$PWD/library" Rscript --vanilla check_install.RInstalled version: 0.1.0GC fraction: 0.5gc_fraction: ....................
══ DONE ════════════════════════════════════════════════════════════════════════The fresh R process imports the installed package and finds its help page.
test_package() runs the installed tests, while test_local() earlier used
the source directory. --install-tests keeps the tests available for this
additional check. Normal package installation does not need to retain them.
Maintain the package contract
Section titled “Maintain the package contract”For another release, update the function, its roxygen block, and its tests
together. Regenerate the help and namespace, change Version in
DESCRIPTION, and build a new archive. Repeat the installation check in a
fresh consumer directory so an older installation cannot hide a missing file.
The source archive can be shared without submitting to CRAN. A CRAN submission is a separate process with maintainer details, repository policies, and platform checks. The R Packages release chapter describes that process when the package is ready for public distribution.
Scientific references
Section titled “Scientific references”Wickham, 2011 describes testthat and its expectations for automated R tests.
Wickham and colleagues, 2026 document how roxygen2 generates R help files and namespace declarations.
Further reading
Section titled “Further reading”The Writing R Extensions manual defines the package structure, metadata, and build commands. Use it to check what an R source archive must contain.
The roxygen2 introduction explains the transformation from source comments to help files. Its namespace guide distinguishes exports from imported names.
The testthat package reference distinguishes source tests, installed tests, and the check entry file. These are the three test contexts used in this lesson.
The R Packages dependency chapter
explains Imports, Suggests, and qualified calls. It helps prevent a package
from working only because a developer happened to attach another library.