Statisticians Advancing in R
for Data Science
Marquette University
STAR-DS - SDSS 2026
In R, the fundamental unit of shareable code is the package.
A package bundles together:
All in one place, easy to share with others.
If you’re here, you already know how to work with packages:
This workshop is about moving from using packages to developing your own.
Why?
Make sure you have:
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.
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.
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/)R packages move through a lifecycle from development to execution:
DESCRIPTION, R/, and optional components.tar.gz file created from source (portable, not yet usable)library() and actively runningBefore creating your R package, you need to choose a name.
A valid R package name must:
.)You cannot use:
-_Once you have a name, create the package using either:
usethis::create_package("mypkg")Both options run the same function under the hood.
R/ folder → for your function codeDESCRIPTION file → metadataNAMESPACE file → exports/importsmypkg.Rproj → RStudio project file.Rbuildignore, .gitignore → build and Git helpers
The DESCRIPTION file provides overall metadata about your package:
Imports, Suggests)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,
knitrPackages listed in DESCRIPTION are not all treated the same.
R distinguishes between required and optional dependencies.
Imports (Required)
Suggests (Optional)
Rule of thumb: If your main functions break without it → use
Imports. Otherwise → useSuggests.
The NAMESPACE file defines the interface of your package.
It controls:
This file is auto-generated by roxygen2, so you typically don’t edit it by hand.
# 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)
In .R files:
To add functionality to your package, you’ll write:
.R scripts in the R/ folderLet’s walk through the process.
All your functions go in the R/ folder.
Each .R file can contain one or more functions.
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.
After writing your function and roxygen2 comments, run:
This will:
Update the NAMESPACE file
Create .Rd help files in the man/ folder
You can also press Ctrl+Shift+D in RStudio.
The src/ folder is used for compiled C/C++ code (Rcpp).
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.
mypkg/
├── R/
│ ├── my_function.R
│ ├── helpers.R
│ └── launchApp.R
├── inst/
│ └── app/
│ ├── ui.R
│ └── server.RFiles inside inst/ are copied into the installed package and can be accessed at runtime.
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
Use usethis to create a new package directory:
This creates:
R/, DESCRIPTION, NAMESPACE
.Rproj, .gitignore, .Rbuildignore
Opens new RStudio project for your package
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.
Imports, Suggests)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.3Let’s include a built-in dataset (mtcars) for simplicity:
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
}.cpp files in the src/ folderR/ folderCreate 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;
}knn_app in the inst/ folderinst/knn_app/ folderR/ folderCreate 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)
}Run the following command to generate docs:
This will:
Add export(knn_pred) to your NAMESPACE
Create man/knn_pred.Rd
In the console:
The output will look like:

Build the package locally:
Now you can use it like any other package:
help("knn_pred")CRAN is the Comprehensive R Archive Network — the main repository for R packages.
Submitting to CRAN means:
install.packages("yourpkg")Make sure your package:
R CMD check with no ERRORs, no WARNINGs, and no (avoidable) NOTEsLICENSESome NOTEs are common (e.g., missing author ORCID), but…
Never submit to CRAN with unaddressed ERRORs or WARNINGs
To reduce NOTEs:
Authors@RTitle and Description are plain textcat() or print() in package code unless essentialUse rhub to simulate CRAN checks on different platforms:
Or test specific platforms:
This helps catch issues that only appear on Windows or macOS.
Use the devtools helper:
This will:
To submit an update:
NEWS.md entryYou can only submit once every 1–2 weeks (per package).
Questions & Discussion