Package Development in R

📘 Introduction

An R package is a collection of functions, datasets, documentation, and metadata organized into a standard directory structure. Package development enables developers to create reusable code, share functionality with others, and distribute software through repositories such as CRAN, Bioconductor, or private repositories.

Information

Developing an R package encourages modular programming, proper documentation, automated testing, and easier code maintenance.

đŸŽ¯ Why Develop R Packages?

  • Reuse code across multiple projects.
  • Share functions with other developers.
  • Organize large codebases efficiently.
  • Create professional, documented software.
  • Distribute applications through package repositories.

đŸ“Ļ Essential Packages for Development

The following packages simplify the package development workflow.

Installing Development Packages

install.packages("devtools")
install.packages("roxygen2")
install.packages("usethis")
install.packages("testthat")
install.packages("pkgdown")

library(devtools)
library(roxygen2)
library(usethis)
library(testthat)
library(pkgdown)

📚 Package Development Workflow

Create Package
Write Functions
Document Code
Test Functions
Build Package
Check Package
Publish Package

📁 Standard Package Structure

Folder/FilePurpose
DESCRIPTIONPackage metadata.
NAMESPACEExported functions and imports.
R/R source code.
man/Generated documentation.
tests/Unit tests.
data/Included datasets.
vignettes/Tutorials and guides.
inst/Additional package resources.

🏗 Creating a New Package

The usethis package simplifies package creation.

Create a Package

library(usethis)

create_package(
  "MyPackage"
)

📝 Writing Package Functions

Functions are stored as individual .R files inside the R/ directory.

Example Function

addNumbers <- function(

  x,
  y

) {

  x + y

}

📖 Documenting Functions with roxygen2

roxygen2 generates documentation directly from specially formatted comments.

roxygen2 Documentation

#' Add Two Numbers
#'
#' Adds two numeric values.
#'
#' @param x First number.
#' @param y Second number.
#'
#' @return Sum of x and y.
#'
#' @export

addNumbers <- function(

  x,
  y

) {

  x + y

}

📄 Generating Documentation

Generate Documentation

library(devtools)

document()

đŸ“Ļ Managing Dependencies

Package dependencies are listed in the DESCRIPTION file.

DESCRIPTION Example

Package: MyPackage
Type: Package
Title: Example Package
Version: 1.0.0
Author: John Doe
Maintainer: John Doe <john@example.com>
Description: Demonstration package.
License: MIT
Imports:
    dplyr,
    ggplot2

📤 Exporting Functions

Exported functions become available to users after installing the package.

Export Using roxygen2

#' @export

addNumbers <- function(

  x,
  y

) {

  x + y

}

đŸ§Ē Unit Testing

The testthat package supports automated testing to verify that functions behave as expected.

Creating a Test

library(testthat)

test_that(

  "Addition works correctly",

  {

    expect_equal(

      addNumbers(
        2,
        3
      ),

      5

    )

  }

)

â–ļ Running Tests

Run All Tests

library(devtools)

test()

🔨 Building the Package

Building creates a distributable package archive.

Build Package

library(devtools)

build()

✔ Checking the Package

Package checking verifies documentation, code quality, examples, and tests.

Check Package

library(devtools)

check()

đŸ“Ĩ Installing the Package

Install Local Package

library(devtools)

install()

🌐 Creating a Package Website

The pkgdown package generates a documentation website automatically.

Build Website

library(pkgdown)

build_site()

📊 Including Data in a Package

Package datasets are typically stored in the data/ directory.

Saving Package Data

studentData <- data.frame(

  Name = c(
    "Alice",
    "Bob"
  ),

  Marks = c(
    85,
    90
  )

)

usethis::use_data(
  studentData,
  overwrite = TRUE
)

📖 Creating Vignettes

Vignettes are long-form tutorials that demonstrate package usage.

Create a Vignette

library(usethis)

use_vignette(
  "getting-started"
)

🌍 Real-World Example

A data science team develops a package containing reusable data cleaning, visualization, and reporting functions. The package is documented with roxygen2, tested using testthat, and shared internally so that all team members use the same reliable functions across projects.

Reusable Data Cleaning Function

#' Remove Missing Values
#'
#' Removes rows containing missing values.
#'
#' @param data Input data frame.
#'
#' @return Cleaned data frame.
#'
#' @export

cleanData <- function(

  data

) {

  na.omit(data)

}

🔄 Package Development Lifecycle

Plan Package
Create Structure
Develop Functions
Document Code
Write Tests
Build and Check
Release Package

📋 Common Development Functions

FunctionPurpose
create_package()Creates a new package.
document()Generates documentation.
build()Builds the package archive.
check()Checks package quality.
install()Installs the local package.
test()Runs unit tests.
build_site()Creates a documentation website.
use_data()Adds datasets to a package.

âš ī¸ Common Mistakes

MistakeExplanationSolution
Missing documentationUsers cannot understand or use package functions effectively.Document every exported function using roxygen2.
Not writing testsBugs may remain undetected.Create automated tests with testthat.
Forgetting to export functionsUsers cannot access public functions.Add the @export tag to exported functions.
Ignoring package check warningsMay cause installation or compatibility issues.Resolve all warnings and errors before publishing.

💡 Best Practices

  • Follow the standard R package directory structure.
  • Document every exported function thoroughly.
  • Write automated tests for important functionality.
  • Run check() before every release.
  • Use meaningful version numbers and maintain a changelog.
  • Keep functions modular, reusable, and well organized.
  • Create vignettes and examples to help users learn the package.

Best Practice

High-quality R packages combine clean code, comprehensive documentation, automated testing, and consistent organization. Using modern development tools such as devtools, roxygen2, usethis, and testthat streamlines development and produces maintainable, professional software.

📝 Summary

Package development transforms reusable R code into organized, documented, and distributable software. In this chapter, you learned how to create package structures, write functions, document code with roxygen2, manage dependencies, export functions, build and check packages, write unit tests using testthat, include datasets, create package websites with pkgdown, and develop vignettes. Mastering package development enables you to build robust, reusable, and professional R libraries that can be shared with the broader R community or within organizations.

>>"A well-designed R package transforms individual scripts into reusable, reliable, and maintainable software for everyone."