30  Software Engineering for Statisticians

30.1 Learning objectives

By the end of this chapter you should be able to:

  • Profile R code with profvis and bench and identify the small set of bottlenecks worth optimizing.
  • Write performance-critical inner loops in C++ via Rcpp and integrate them into an R package.
  • Build a defensible R package with usethis and devtools, including documentation, tests, continuous integration, and pkgdown documentation.
  • Design a testthat test suite that covers correctness, numerical stability, and regression, and explain why each layer is needed.
  • Use AI-assisted coding tools (LLM in IDE, Claude Code, GH Copilot) productively without ceding the engineering judgment that distinguishes maintainable code from syntactically correct code.
  • Recognize the warning signs of unmaintainable research code and apply the small set of practices that prevent them.

30.2 Orientation

Statisticians produce code as a research artifact. Most of that code is throwaway: a one-off analysis, a simulation study, a figure script. Some of it, however, becomes a library that collaborators use, a package on CRAN, or the computational core of a clinical decision tool. The skills that produce maintainable, performant, defensible software are not the same as the skills that produce a clean Quarto report. Unfortunately, they are routinely under-taught in statistics curricula.

This chapter is a practical foundation in those skills. We shall cover profiling and performance, the C++/R interface through Rcpp, R-package authorship, and testing strategy. We then discuss the working pattern of using AI assistance well, and we close with a worked example that optimizes a sequential algorithm. The running thread is that the discipline of statistical software engineering is the same discipline as the rest of software engineering, with one difference. That is, numerical correctness is harder to verify, and easier to compromise silently, than typical software correctness.

30.3 The statistician’s contribution

LLMs are competent at writing R code, structuring tests, and refactoring functions. They do not understand which parts of a numerical algorithm are correctness-critical, or which optimizations preserve numerical equivalence. Nor can they tell when an apparent speedup hides a regression. The statistician owns these judgments.

(Judgment 1.) Profile, then optimize. The most common engineering error in research code is optimizing the wrong thing. A one-line change to the algorithm can recover 50× speedups. By contrast, rewriting an irrelevant inner loop in C++ can buy 1.05× at the cost of three days of debugging. The statistician’s role is to insist on profiling before optimizing and to keep the engineering effort proportional to the bottleneck. LLMs will readily rewrite anything in Rcpp, whether or not a profile justifies the rewrite.

(Judgment 2.) Numerical equivalence is not optional. A ‘speedup’ that changes outputs by \(10^{-12}\) might be fine, whereas one that changes outputs by \(10^{-4}\) might indicate a broken algorithm. The statistician verifies that an optimized version produces identical results to the reference implementation on a battery of test cases. Here ‘identical’ means identical up to machine precision, with explicit tolerances. Skipping this check has produced silently wrong published results in the literature.

(Judgment 3.) Tests are the documentation that runs. Code without tests rots. Code with comprehensive tests can be refactored aggressively, ported to new platforms, and trusted by collaborators. The work of writing tests is also the work of figuring out the boundaries of the algorithm. That is, we learn what inputs are valid, what edge cases must be handled, and what numerical regime is supported. The statistician treats this as part of the work, not as overhead added at the end.

30.4 Profiling: profvis and bench

R is famously slow at loops; it is also famously fast at vectorized operations on the right primitives. The useful question is therefore where our code is slow, and profiling answers it.

profvis (Chang et al., 2024) wraps R’s sampling profiler in an interactive flame graph. The workflow is as follows:

library(profvis)
profvis({
  result <- run_my_analysis(data)
})

The output identifies which functions consume the most time. It also shows how much of that time is spent in their own bodies versus delegated to children. A familiar pattern recurs: 80% of the time is in 20% of the code. Within that 20%, a single line typically accounts for most of the budget. Common culprits are a for loop over rows of a data frame, an unnecessary rbind() in a loop, or a poorly configured lm.fit().

bench (Hester, 2024) is the right tool for microbenchmarks. To illustrate, consider a comparison of two implementations:

library(bench)
mark(
  base = sapply(x, sqrt),
  vec = sqrt(x),
  iterations = 100,
  check = TRUE
)

check = TRUE confirms that the implementations produce equal results. We would always set it. Many proposed ‘faster’ implementations turn out to be both faster and wrong, and the check catches them.

bench::press() sweeps a parameter and produces a performance-by-size table. It is the right tool when the question is ‘how does runtime scale with \(n\)’ rather than ‘which is faster on this fixed problem.’

Two practical patterns recover most R speedups:

  1. Vectorize. Replace explicit for loops with element-wise operations on whole vectors or matrices.
  2. Avoid copy-on-modify in tight loops. Pre-allocate output containers, and use data.table’s in-place modification where helpful. Never grow a vector with c(x, new_value) in a loop.

When neither applies, as with a genuinely sequential algorithm whose state depends on earlier iterations, the next move is C++.

30.5 Rcpp: the C++ escape hatch

Rcpp (Eddelbuettel & François, 2011) provides a clean interface between R and C++. The modal workflow is as follows:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector cumsum_cpp(NumericVector x) {
  int n = x.size();
  if (n == 0) return NumericVector(0);
  NumericVector out(n);
  out[0] = x[0];
  for (int i = 1; i < n; i++) {
    out[i] = out[i-1] + x[i];
  }
  return out;
}

Rcpp::sourceCpp("cumsum.cpp") compiles and exposes the function. For C++ code that lives inside an R package, devtools::document() regenerates the RcppExports.cpp shim. The C++ functions then become callable from R like any other package function.

Rcpp is the right tool when:

  • The algorithm is genuinely sequential (cannot be vectorized).
  • The R version is order-of-magnitude slower than needed.
  • The C++ version will be reused, justifying the engineering investment.

On the other hand, Rcpp is the wrong tool when the speedup is small, when an existing R-side primitive does the job, or when the correctness of the C++ version cannot be verified against a reference.

RcppArmadillo (Eddelbuettel & Sanderson, 2014) adds linear-algebra primitives via Armadillo, and it is the standard for moving matrix-shaped algorithms into C++. RcppEigen does the same with Eigen. It is preferred when interoperability with C++ libraries that use Eigen is needed.

Question. A colleague has a function that loops over 1000 groups in a data frame, fits a small regression model to each group, and stores the coefficient. The loop takes 30 seconds. They propose rewriting it in Rcpp. Is that the right next step?

Answer.

No. The right next step is to profile, for example with profvis::profvis() or Rprof(). The cost of each fit lies partly in already-compiled C code (the QR solver behind lm.fit()) and partly in R-level overhead such as model.frame() and model.matrix(). Rewriting the wrapping loop in Rcpp touches neither, so it would buy little. Moreover, 30 seconds is far more than 1000 small fits should take. On an Apple M1 laptop, a loop of 1000 lm() calls with 10 to 30 observations per group took about 0.3 seconds. The time is therefore most likely spent elsewhere in the loop body, and the profile will show where. If the per-fit overhead does turn out to dominate, we may build each design matrix once and call lm.fit() directly, which took roughly 0.1 seconds in the same test, or parallelize the loop (Chapter 24). One tempting alternative is problematic. A single lm() call with a per-group factor produces all 1000 sets of coefficients, but its dense design matrix has 2000 columns. In the same test that fit took tens of seconds, roughly 100 times slower than the loop. Timings will differ on other hardware.

30.6 R-package authorship

A function that grows beyond a single script is a candidate for a package. The mechanics, with usethis and devtools, are mature enough that the engineering overhead is small.

usethis::create_package("~/projects/mypkg")
usethis::use_mit_license("rgtlab curriculum team")
usethis::use_testthat()
usethis::use_github_action("check-standard")
usethis::use_roxygen_md()
usethis::use_pkgdown()

A defensible package has, at minimum:

  • DESCRIPTION declaring dependencies, license, and version.
  • R/ source files with roxygen2 documentation on every exported function.
  • tests/testthat/ with tests for every exported function.
  • A NEWS.md logging changes.
  • A README.md with a minimal worked example.
  • CI configured so every push runs R CMD check on multiple platforms.

The usethis calls above set all of this up. The remaining work is writing the code and the tests.

For packages that will be released widely, three further considerations apply.

  • CRAN release through devtools::release(). The CRAN policies are strict and submission is iterative, so we would allow time.
  • pkgdown site built from roxygen2 + vignettes and hosted on GitHub Pages. It is the de facto standard for R package documentation, and users expect it.
  • Versioning follows semantic versioning conventions (MAJOR.MINOR.PATCH). Breaking changes increment MAJOR; new features increment MINOR; bug fixes increment PATCH.

30.7 Testing strategy

A typical research package needs three layers of tests.

Correctness tests verify that the function returns the right answer on inputs with a known answer.

test_that("ols_fit recovers known coefficients", {
  set.seed(228)
  X <- cbind(1, rnorm(100))
  beta_true <- c(0.5, 1.2)
  y <- X %*% beta_true + rnorm(100, 0, 0.1)
  fit <- ols_fit(y, X)
  expect_equal(fit$coef, beta_true, tolerance = 0.05)
})

Numerical stability tests verify that the function behaves correctly on inputs that stress the algorithm.

test_that("ols_fit handles near-collinear design", {
  x <- runif(100)
  X <- cbind(1, x, x + 1e-8)
  expect_warning(ols_fit(rnorm(100), X), "collinear")
})

Regression tests verify that a known input produces a specific known output, byte-for-byte. They catch silent behavior changes from refactors.

test_that("ols_fit output has not changed", {
  expect_snapshot_value(
    ols_fit(testdata$y, testdata$X)$coef,
    style = "deparse"
  )
})

testthat::expect_snapshot() and expect_snapshot_value() (Wickham, 2024) make regression tests inexpensive. The first run records the output, and subsequent runs compare against it.

For packages that wrap numerical algorithms, a fourth layer consists of reference-implementation tests. In these, the package output is compared to a slower but trusted reference, such as the closed-form solution or the output from a well-established package. These tests catch subtle algorithmic errors that pass the correctness and numerical-stability tests but produce wrong answers in specific regimes.

30.8 Working with AI assistants

Coding assistants (Copilot, Cursor, Claude Code, or similar) are now standard tools. On the one hand, used well, they speed up boilerplate, accelerate refactors, and surface documentation. On the other, used badly, they produce subtly wrong code that passes the eye test and fails in production.

We see three patterns of productive use.

Boilerplate. Roxygen documentation skeletons, package file templates, ggplot themes, and recipe steps in tidymodels fall in this category. Here the LLM is producing code that any sufficiently experienced developer would write the same way. The verification cost is low because the code is boilerplate.

Refactor proposals. ‘Rewrite this function to avoid the nested loop’ is a request the LLM handles well, if we verify equivalence. The verification cost is moderate, usually a bench::mark() with check = TRUE and a testthat run, and the time saved is substantial.

Documentation explanations. Questions such as ‘what does this dplyr expression do’ or ‘why does my Stan model produce this warning’ often get a useful answer, which the LLM can produce from internalized documentation. The stakes are lower, and verification consists of reading the result and confirming that it matches our understanding.

There are also three patterns to avoid.

Numerical-algorithm authorship without verification. Asking the LLM to ‘implement the L-BFGS update’ or ‘write a sparse Cholesky’ is asking for code that is plausibly correct but very likely wrong in the corners. We would use existing libraries (optim, Matrix, RcppEigen). An LLM-authored numerical kernel is warranted only when no library exists, and it must then be verified exhaustively against a reference.

Test-skipping. LLMs will gladly remove tests that fail to pass after a refactor. We should do the opposite, that is, treat a failing test as a report of a behavior change and investigate the change.

Wholesale generation of unfamiliar code. Asking the LLM for 800 lines of code in a domain we have never worked in is asking to deploy code we cannot review. The defense is to break the work into pieces small enough that we can review each one.

Practitioners in 2026 name this distinction directly. ‘Vibe coding’ is prompting a model, accepting the result, and running it without review. It is acceptable for a disposable script but not for anything we intend to keep. ‘Agentic coding’, or ‘agentic engineering’, is the disciplined alternative. An agent plans, writes, and runs code in a loop, and a human still reviews the diff against real acceptance criteria before trusting it. The three patterns to avoid above amount to vibe coding, while the three productive patterns are agentic engineering done well.

A common framing treats the LLM as a fast junior collaborator. It will type faster than we do and produce more lines of code per hour. However, it will not catch the numerical edge cases, judge the right level of abstraction, or know what to test. Those judgments remain ours.

30.9 Worked example: optimizing a sequential algorithm

We illustrate the profile, optimize, and verify cycle on a sequential filter (a one-step Kalman filter for a state-space model) that starts as a slow R loop.

kalman_r <- function(y, x0, P0, A, H, Q, R) {
  n <- length(y)
  x_hat <- numeric(n)
  P <- numeric(n)
  x_pred <- x0; P_pred <- P0
  for (t in seq_len(n)) {
    K <- P_pred * H / (H * P_pred * H + R)
    x_hat[t] <- x_pred + K * (y[t] - H * x_pred)
    P[t] <- (1 - K * H) * P_pred
    x_pred <- A * x_hat[t]
    P_pred <- A * P[t] * A + Q
  }
  list(x = x_hat, P = P)
}

We profile it on a 100,000-step series:

library(profvis)
y <- rnorm(1e5)
profvis({
  out <- kalman_r(y, 0, 1, 1, 1, 0.1, 0.5)
})
# 1.4 seconds; 95% in the for loop body

Vectorization is not available, because each iteration depends on the previous one. The remaining options are Rcpp or accepting the runtime. The Rcpp version is as follows:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List kalman_cpp(NumericVector y, double x0, double P0,
                double A, double H, double Q, double R) {
  int n = y.size();
  NumericVector x_hat(n), P(n);
  double x_pred = x0, P_pred = P0;
  for (int t = 0; t < n; t++) {
    double K = P_pred * H / (H * P_pred * H + R);
    x_hat[t] = x_pred + K * (y[t] - H * x_pred);
    P[t] = (1.0 - K * H) * P_pred;
    x_pred = A * x_hat[t];
    P_pred = A * P[t] * A + Q;
  }
  return List::create(_["x"] = x_hat, _["P"] = P);
}

We then benchmark the two versions with verification:

library(bench)
mark(
  R = kalman_r(y, 0, 1, 1, 1, 0.1, 0.5),
  cpp = kalman_cpp(y, 0, 1, 1, 1, 0.1, 0.5),
  iterations = 50, check = TRUE
)
# R    1.4 s
# cpp  3.2 ms
# check passed: outputs equal under all.equal()

The C++ version is about 400× faster. Its output agrees with the R version within the tolerance of all.equal(), which is the comparison that check = TRUE performs. We would expect the agreement to be essentially exact, since the implementations use the same algorithm with the same arithmetic order. Bit-level identity, however, would require a separate identical() check. The check = TRUE is the non-negotiable part. An Rcpp implementation that is fast but produces different output is a regression that must be caught at benchmark time, not in production.

As a rule of thumb, Rcpp is worth it when the loop is genuinely sequential and dominates runtime. In that case we verify equivalence with bench::mark(check = TRUE) or a snapshot test.

30.10 Collaborating with an LLM on software engineering

LLMs are productive on boilerplate, refactors, and documentation. Unfortunately, they are unreliable on performance reasoning, on numerical correctness in custom algorithms, and on test design. We consider three representative prompts.

Prompt 1: ‘Refactor this 200-line function for clarity.’ Provide the function and any test cases.

What to watch for. The LLM will produce a refactored version with smaller helpers and clearer naming. It may change behavior without saying so, for example in a default argument, a sort order, or an edge-case branch. It rarely confirms the refactor by running the test suite.

Verification. We run the test suite before and after. We also diff the output of the function on a representative input before and after. Either a passing test suite or a byte-identical output diff is acceptable evidence; both are better.

Prompt 2: ‘Write tests for this exported function.’ Provide the function.

What to watch for. The LLM will produce a small set of correctness tests on happy-path inputs. It will rarely generate edge-case tests (empty inputs, NA values, boundary values) without prompting. It will not write regression tests against the current behavior, because it does not know what the current behavior produces.

Verification. We use the LLM-generated tests as a starting point. We then add edge-case tests ourselves: empty input, NA input, single-element input, and very large input. We also add a snapshot regression test on a representative case. Lastly, we mutation-test; that is, we deliberately break the function and check that at least one test fails.

Prompt 3: ‘Optimize this slow function.’ Provide the function and the profiling output.

What to watch for. The LLM will propose vectorization, preallocation, or Rcpp. It will sometimes propose all three at once. It will rarely run a benchmark to confirm that the proposed optimization actually helps. It is happy to ship a ‘faster’ version that is the same speed or slower.

Verification. We run bench::mark(check = TRUE) against the original. If the optimized version is no faster, we revert. If it is faster but fails the check, we have a correctness regression masquerading as a speedup, and we revert and investigate.

Across all three prompts, the LLM speeds up the typing but not the engineering decisions. We would treat it as a fast typist with no judgment and supply the judgment ourselves.

30.11 Principle in use

Three habits define defensible software engineering work:

  1. Profile before optimizing; verify after. Optimization work without a profile is guesswork, and a speedup is not established until numerical equivalence has been verified. Both habits are inexpensive, and both are routinely skipped.

  2. Treat the test suite as the spec. We write tests as we write the function, not after. The tests are how we discover the boundary cases the function must handle; they are also how we prove the function works. A function without tests is undocumented and un-refactorable.

  3. Match engineering effort to artifact lifespan. A one-off analysis script does not need a package structure or CI, whereas a library that collaborators will use does. We apply the right level of engineering to the right artifact, since under-engineering one and over-engineering the other are equally costly.

30.12 Exercises

  1. Take a research script of your own and profile it with profvis. Identify the slowest function. Re-profile after vectorizing it. Document the speedup.

  2. Implement a sequential algorithm of your choice (e.g., the Viterbi algorithm for HMMs) in pure R and in Rcpp. Benchmark with check = TRUE. Document the speedup and the threshold problem size at which the Rcpp version becomes worth using.

  3. Convert a research script into a package using usethis::create_package(). Add at least one exported function with roxygen2 documentation, three testthat tests (correctness, edge case, snapshot), and a CI workflow with usethis::use_github_action('check-standard').

  4. Write a regression test against a non-trivial function in your codebase using expect_snapshot_value(). Modify the function to produce a different output; confirm the test fails. Restore the function; confirm the test passes.

  5. Pick a function written entirely by an LLM. Write a property-based test (e.g., ‘the function is monotone in its first argument’) without consulting the LLM. Did the LLM-authored function pass?

30.13 Further reading

  • Wickham & Bryan (2023), R Packages, 2nd edition (https://r-pkgs.org/). The canonical reference for R-package authorship.
  • Eddelbuettel (2013), Seamless R and C++ Integration with Rcpp. The book-length treatment of the C++/R interface.
  • Wickham (2024), the testthat documentation and the chapter in R Packages.
  • The profvis and bench package vignettes are exemplary applied references.