Develop your own professional R package

Statisticians Advancing in R
for Data Science

Mehdi Maadooliat, Jaihee Choi and Daniel Cirkovic

Marquette University
STAR-DS - SDSS 2026

R Packages: The Fundamental Unit

In R, the fundamental unit of shareable code is the package.

A package bundles together:

  • Code
  • Data
  • Documentation
  • Tests

All in one place, easy to share with others.

You Already Use Packages!

If you’re here, you already know how to work with packages:

  • Install a package from CRAN:

    install.packages("x")
  • Use a package in R:

    library("x")
  • Get help on them with

    package?x
    help(package = "x")

Goal of This Talk

This workshop is about moving from using packages to developing your own.

Why?

  • To share your code with others
  • To make your code easy to install, use, and learn
  • To save yourself time with conventions and structure

System Setup

Make sure you have:

  • The latest version of R.
  • The latest version of RStudio.

Required Packages:

Install the essential development tools:

install.packages(c("devtools", "roxygen2", "testthat", "knitr"))

Key Packages

  • devtools: Simplifies package development by wrapping complex workflows into easy commands

  • roxygen2: Generates documentation from special comments in your function code

  • testthat: Provides a framework for unit testing and ensures your functions work correctly and safely over time

  • knitr: Powers dynamic report generation and vignette building that integrates code, results, and text using R Markdown

These tools help automate, test, document, and share your package like a pro.

Package Structure

Directory layout

  mypkg/
  ├── DESCRIPTION         # Package metadata
  ├── NAMESPACE           # Exported functions & imports
  ├── R/                  # Your R functions
  └── man/                # Auto-generated documentation

💡 Tip: Many folders in an R package are optional and included as needed.

Directory layout

mypkg/
├── DESCRIPTION         # Package metadata
├── NAMESPACE           # Exported functions & imports
├── R/                  # Your R functions
├── src/                # C/C++ code (Rcpp, compiled extensions)
├── man/                # Auto-generated documentation
├── tests/              # Unit tests with testthat
├── vignettes/          # Long-form documentation (Rmd)
├── data/               # Data sets (.rda files)
└── inst/               # Installed files (e.g., app/, extdata/)

Package States in R

R packages move through a lifecycle from development to execution:

  • Source: editable folder with DESCRIPTION, R/, and optional components
  • Bundled: compressed .tar.gz file created from source (portable, not yet usable)
  • Binary: precompiled package for a specific operating system
  • Installed: unpacked into an R library and ready to use
  • In-memory: loaded into R session via library() and actively running

Transitioning Between States

Screenshot of Pagerank

Create a Package

Before creating your R package, you need to choose a name.

A valid R package name must:

  1. Contain only letters, numbers, and periods (.)
  2. Start with a letter
  3. Not end with a period

You cannot use:

  • Hyphens -
  • Underscores _

Creating Your Package

Once you have a name, create the package using either:

  • usethis::create_package("mypkg")
  • RStudio UI:
    File → New Project → New Directory → R Package

Both options run the same function under the hood.

What Gets Created?

  • R/ folder → for your function code
  • DESCRIPTION file → metadata
  • NAMESPACE file → exports/imports
  • mypkg.Rproj → RStudio project file
  • .Rbuildignore, .gitignore → build and Git helpers

Screenshot of Pagerank

DESCRIPTION File

The DESCRIPTION file provides overall metadata about your package:

  • Package name and version
  • Author and maintainer info
  • Dependencies (Imports, Suggests)
  • Description and license
  • Build-related metadata

Sample DESCRIPTION File

Package: mypkg
Title: What the Package Does (One Line, Title Case)
Version: 0.0.0.9000
Authors@R: 
    person("First", "Last", , "first.last@example.com", role = c("aut", "cre"))
Description: What the package does (one paragraph).
License: `use_mit_license()`, `use_gpl3_license()` or friends to pick a
    license
Encoding: UTF-8
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.3.3

Imports:
    ggplot2,
    dplyr

Suggests:
    testthat,
    knitr

Imports vs. Suggests

Packages listed in DESCRIPTION are not all treated the same.

R distinguishes between required and optional dependencies.

Imports (Required)

  • Needed for your package to work
  • Installed automatically when your package is installed
  • Available at runtime

Suggests (Optional)

  • Used for examples, tests, or vignettes
  • Not required for core functionality
  • Installed only if explicitly requested

Rule of thumb: If your main functions break without it → use Imports. Otherwise → use Suggests.

NAMESPACE File

The NAMESPACE file defines the interface of your package.

It controls:

  • What functions your package exports
  • What functions it imports from other packages
  • S3/S4 method registrations (if needed)

This file is auto-generated by roxygen2, so you typically don’t edit it by hand.

Example: NAMESPACE File

# Generated by roxygen2: do not edit by hand

export(my_function)
import(ggplot2)
importFrom(Rcpp,evalCpp)
importFrom(shiny,runApp)
useDynLib(my_function, .registration = TRUE)
  • export() — makes a function available to users

  • import() — brings in all exported objects from a package

  • importFrom() — imports specific functions

  • useDynLib() — links compiled code (C/C++/Fortran) to your package. Required when your package uses compiled routines (e.g., via Rcpp)

How to Generate NAMESPACE

In .R files:

#' @export
r_func <- function(x) { ... }

In .cpp files:

// [[Rcpp::export]]
double myRcpp-func(int x, double y) { ... }

Functions & Documentation

To add functionality to your package, you’ll write:

  • Functions — saved as .R scripts in the R/ folder
  • Documentation — using roxygen2 comments above each function

Let’s walk through the process.

Code Placement

All your functions go in the R/ folder.

mypkg/
├── R/
│   ├── my_function.R
│   └── helpers.R

Each .R file can contain one or more functions.

Documenting Functions with Roxygen2

Use special comments starting with #' to write function documentation:

#' Sum of Square Function
#'
#' This function computes the Sum of Squares of a numeric vector
#' 
#' @param x Numeric vector
#' @return Numeric sum of x
#'
#' @examples
#' x <- 1:5
#' y <- my_function(x)
#' print(y)
#'
my_function <- function(x) sum(x^2)

This will generate help files in the man/ folder.

Generate Documentation

After writing your function and roxygen2 comments, run:

devtools::document()

This will:

  • Update the NAMESPACE file

  • Create .Rd help files in the man/ folder

You can also press Ctrl+Shift+D in RStudio.

src/ Folder and Rcpp Integration

The src/ folder is used for compiled C/C++ code (Rcpp).

  • Contains .cpp files
  • Requires Rcpp in DESCRIPTION
mypkg/
├── src/
│   └── my_function.cpp
├── R/
│   ├── my_function.R
│   └── helpers.R

inst/ Folder and Shiny App Integration

The inst/ folder is for extra files your package needs, but that are not R code, such as a Shiny app.

A common pattern is to bundle a Shiny app inside your package so users can launch it with a single function.

  • Useful when your package includes a method users may want to explore interactively
  • Keeps analysis code and interface together
  • Makes your package easier to demonstrate and teach

Where Does the Shiny App Go?

mypkg/
├── R/
│   ├── my_function.R
│   ├── helpers.R
│   └── launchApp.R
├── inst/
│   └── app/
│       ├── ui.R
│       └── server.R
  • ui.R defines the layout and user inputs
  • server.R defines the reactive logic
  • launchApp.R provides a simple launcher function

Files inside inst/ are copied into the installed package and can be accessed at runtime.

Build a Simple Package from Scratch

We will be using the knn_pred() function from our previous lessons to build an R package that incorporates Rcpp as well as launch the shiny app.

  • Step 1: Create Your Package

  • Step 2: Edit Package Metadata (DESCRIPTION)

  • Step 3: Add a Dataset

  • Step 4: Write Your Functions (R code in R/)

  • Step 5: Add Supporting Files (src/ for Rcpp/C++, inst/ for apps and extras)

  • Step 6: Document Your Functions

  • Step 7: Load and Check the Package

  • Step 8: Build and Install the Package

1. Create Your Package

Use usethis to create a new package directory:

usethis::create_package("KNNreg")

This creates:

  • R/, DESCRIPTION, NAMESPACE

  • .Rproj, .gitignore, .Rbuildignore

  • Opens new RStudio project for your package

2. Edit Package Metadata (DESCRIPTION)

After creating your package, the first thing to do is update the DESCRIPTION file.

This file defines the identity and structure of your package.

  • Set the package name, title, and description
  • Add author and maintainer information
  • Specify dependencies (Imports, Suggests)
  • Define license and encoding

Sample DESCRIPTION File

Package: KNNreg
Type: Package
Title: k-Nearest Neighbors Regression with Shiny App
Version: 0.0.1
Date: 2026-03-19
Authors@R: c(person("Daniel", "Cirkovic", role = c("aut")), person("Jaihee", "Choi", role = c("aut")), person("Mehdi", "Maadooliat", role = c("aut", "cre"), email = "mehdi.maadooliat@marquette.edu"))
Description: kNN regression functions and an interactive Shiny app.
License: GPL (>= 2)
Imports: Rcpp (>= 1.1.1), shiny, ggplot2
LinkingTo: Rcpp
Encoding: UTF-8
RoxygenNote: 7.3.3

3. Add a Dataset

Let’s include a built-in dataset (mtcars) for simplicity:

usethis::use_data(mtcars, overwrite = TRUE)

This creates a data/mtcars.rda file — accessible via

KNNreg::mtcars

4. Write Your Functions

  • Create function files in the R/ folder.

  • Keep important functions in separate files.

  • Place helper functions together in a single file.

  • This structure keeps your project organized and maintainable.

Create a new file: R/knn_pred.R

knn_pred <- function(train_x, train_y, test_x, k) {
  # Coerce types
  train_x <- as.matrix(train_x)
  test_x  <- as.matrix(test_x)
  train_y <- as.numeric(train_y)

  # Scale train and test appropriately
  train_x <- scale(train_x)
  # Extract the mean and sd used
  train_mean <- attr(train_x, "scaled:center")
  train_sd <- attr(train_x, "scaled:scale")
  # Apply the same transformation to test data
  test_x <- scale(test_x, center = train_mean, scale = train_sd)

  n <- nrow(train_x)
  p <- ncol(train_x)
  m <- nrow(test_x)

  # Store predictions
  preds <- numeric(m)
  # Store ids of k nearest neighbors
  ids <- numeric(m * k)

  for (j in seq_len(m)) {

    # Squared Euclidean distances using matrix ops (fast):
    # t(train_x) is p x n; subtract p-vector test_x[j,]; colSums -> length n
    dists <- colSums((t(train_x) - test_x[j, ])^2)

    # Indices of k smallest distances (full sort, simple & reliable)
    idx_k <- order(dists)[seq_len(k)]

    # Mean of neighbor labels
    preds[j] <- mean(train_y[idx_k])

    # Store ids of nearest neighbors
    # ids of vars
    ids[((j-1) * k + 1):(j * k)] <- idx_k
  }

  out = list("preds" = preds, "ids" = ids)

  out
}

5. Add Supporting Files - src/

  • Add .cpp files in the src/ folder
  • Compiled code is linked to R through Rcpp
  • Called from standard R functions in the R/ folder

Create a new file: src/knn_pred.cpp

// [[Rcpp::depends(Rcpp)]]
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List knn_pred_cpp(NumericMatrix train_x,
                           NumericVector train_y,
                           NumericMatrix test_x,
                           int k) {
  int n = train_x.nrow(), 
    p = train_x.ncol(), 
    m = test_x.nrow();
  NumericVector preds(m);
  int id_length = m * k;
  IntegerVector ids(id_length);

  
  for (int j = 0; j < m; ++j) {
    // compute and store (distance,index)
    std::vector<std::pair<double,int>> dists(n);
    for (int i = 0; i < n; ++i) {
      double sumsq = 0;
      for (int d = 0; d < p; ++d) {
        double diff = train_x(i,d) - test_x(j,d);
        sumsq += diff * diff;
      }
      dists[i] = std::make_pair(sumsq, i);
    }
    // partial sort to get k nearest
    std::nth_element(dists.begin(), dists.begin() + k, dists.end(),
                     [](auto &a, auto &b){ return a.first < b.first; });
    double s = 0;
    for (int r = 0; r < k; ++r) {
      s += train_y[dists[r].second];
      ids[j * k  + r] = std::get<1>(dists[r]);
    }
    preds[j] = s / k;
  }
  
  List ret;
  ret["preds"] = preds;
  ret["ids"] = ids + 1;
  
  return ret;
}

5. Add Supporting Files - inst/

  • Create a new folder knn_app in the inst/ folder
  • Add Shiny app files in the inst/knn_app/ folder
  • The app UI and server logic live inside the package
  • Called from a launcher function in the R/ folder

Create a new file: inst/knn_app/server.R

library(shiny)
library(ggplot2)

server.KNNreg <- function(input, output, session) {

  # Functions for splitting and plotting
  make_split <- function(data, prop = 0.7) {
    n <- nrow(data)
    train_idx <- sample(n, size = floor(prop * n))
    list(train = data[train_idx, ], test = data[-train_idx, ])
  }

  segment_df <- function(train_x, test_x, ids, k){
    train_x <- as.matrix(train_x)
    test_x  <- as.matrix(test_x)
    n <- nrow(train_x); p <- ncol(train_x); m <- nrow(test_x)
    test_x_out = test_x[rep(1:m, each = k), ]
    train_x_out = train_x[ids, ]
    out = as.data.frame(cbind(test_x_out, train_x_out))
    colnames(out) <- c(paste0("test_", colnames(train_x)), 
                       paste0("train_", colnames(train_x)))
    out
  }

  # Reactive train/test split
  split <- eventReactive(input$resample, {
    make_split(mtcars, prop = 0.92)
  }, ignoreNULL = FALSE)
  
  # Compute fitted (train) and predicted (test)
  fitted_vals <- reactive({
    d_train <- split()$train
    knn_pred(d_train[, c("wt", "qsec")], d_train[, c("mpg")], 
             d_train[, c("wt", "qsec")], input$k, input$backend)
  })
  predicted <- reactive({
    d_train <- split()$train
    d_test <- split()$test
    knn_pred(d_train[, c("wt", "qsec")], d_train[, c("mpg")], 
             d_test[, c("wt", "qsec")], input$k, input$backend)
  })
  
  mse <- function(obs, pred) mean((obs - pred)^2)
  r2  <- function(obs, pred) 1 - (sum((obs - pred)^2) / sum((obs - mean(obs))^2))

  # Training performance
  output$trainPerf <- renderPrint({
    obs <- split()$train$mpg
    cat("Training set:\n")
    cat("  MSE =", round(mse(obs, fitted_vals()$preds), 3),
        "  R² =", round(r2(obs, fitted_vals()$preds), 3), "\n")
  })

  # Test performance
  output$testPerf <- renderPrint({
    obs <- split()$test$mpg
    cat("Test set:\n")
    cat("  MSE =", round(mse(obs, predicted()$preds), 3),
        "  R² =", round(r2(obs, predicted()$preds), 3), "\n")
  })

  # Plot showing k nearest neighbors
  output$predPlot <- renderPlot({
    d_train <- split()$train
    d_test <- split()$test
    d_test$id = 1:nrow(d_test)
    
    nn <- segment_df(d_train[, c("wt", "qsec")], 
                     d_test[, c("wt", "qsec")], 
                     predicted()$ids, input$k)
    
    d_test$pred <- predicted()$preds
    
    ggplot() +
      geom_segment(aes(x = test_wt, xend = train_wt, 
                       y = test_qsec, yend = train_qsec), 
                   color = "grey50", linetype = "dotted",
                   data = nn) +
      geom_point(aes(x = wt, y = qsec, color = mpg), 
                 size = 2, data = d_train) +
      geom_text(aes(x = wt, y = qsec, color = pred, label = id), 
                size = 5, fontface = "bold", data = d_test) +
      scale_color_gradient(low = "#6A00A8FF", high = "#FCA636FF") +
      theme_classic() +
      labs(x = "wt", y = "qsec")
  })

  # Table of test predictions
  output$predTable <- renderTable({
    d_test <- split()$test
    data.frame(
      id = 1:nrow(d_test),
      car = rownames(d_test),
      actual = round(d_test$mpg,2),
      predicted = round(predicted()$preds,2)
    )
  }, rownames = FALSE)
}

6. Document Your Functions

Run the following command to generate docs:

devtools::document()

This will:

  • Add export(knn_pred) to your NAMESPACE

  • Create man/knn_pred.Rd

Example: NAMESPACE File

# Generated by roxygen2: do not edit by hand

export(knn_pred)
export(run_knn_app)
import(ggplot2)
importFrom(Rcpp,evalCpp)
importFrom(shiny,runApp)
useDynLib(KNNreg, .registration = TRUE)

7. Load and Test the Package

In the console:

devtools::load_all()

Check to make sure there are no issues with your package compiling:

devtools::check()

The output will look like:

Screenshot of Pagerank

8. Build and Install the Package

Build the package locally:

devtools::build()

Install it:

devtools::install()

Now you can use it like any other package:

library(KNNreg)

# Simulate training and test data
train_x <- matrix(rnorm(50), nrow = 10)
train_y <- rnorm(10)
test_x <- matrix(rnorm(20), nrow = 4)

# Set number of nearest neighbors
k <- 3

# Run the kNN algorithm
knn_pred(train_x, train_y, test_x, k, method = "cpp") # test C++ backend

help("knn_pred")

Screenshot of Pagerank

Submitting Your Package to CRAN

  1. CRAN Submission: Overview
  2. Requirements Before Submission
  3. Handling NOTEs and WARNINGs
  4. Simulate a CRAN Check
  5. Submit to CRAN

1. CRAN Submission: Overview

CRAN is the Comprehensive R Archive Network — the main repository for R packages.

Submitting to CRAN means:

  • Your package is publicly available
  • It passes strict quality checks
  • It becomes accessible via install.packages("yourpkg")

2. Requirements Before Submission

Make sure your package:

  • Passes R CMD check with no ERRORs, no WARNINGs, and no (avoidable) NOTEs
  • Has proper documentation for all exported functions
  • Has a valid LICENSE
  • Uses a CRAN-acceptable package name
  • Has examples that run in < 5 seconds

Run:

devtools::check()

3. Handling NOTEs and WARNINGs

Some NOTEs are common (e.g., missing author ORCID), but…

Never submit to CRAN with unaddressed ERRORs or WARNINGs

To reduce NOTEs:

  • Add your ORCID via Authors@R
  • Ensure Title and Description are plain text
  • Avoid using cat() or print() in package code unless essential

4. Simulate a CRAN Check

Use rhub to simulate CRAN checks on different platforms:

rhub::check_for_cran()

Or test specific platforms:

rhub::check(platform = "windows-x86_64-release")

This helps catch issues that only appear on Windows or macOS.

5. Submit to CRAN

Use the devtools helper:

devtools::release()

This will:

  • Check your package one final time
  • Ask you to confirm
  • Open the CRAN web form in your browser
  • Help generate an email to CRAN maintainers

What Happens After Submission?

  • You’ll get an automated confirmation email
  • Within ~24–72 hours, a CRAN maintainer will review your package
  • They may:
    • Accept it immediately
    • Request fixes or clarifications
    • Reject with detailed reasons

Updating a CRAN Package

To submit an update:

  • Bump the version (e.g., from 1.0.0 → 1.0.1)
  • Add a clear NEWS.md entry
  • Ensure compatibility with current R version and dependencies
  • Follow the same submission process

You can only submit once every 1–2 weeks (per package).

Resources & Further Reading

Thank you!

Questions & Discussion