01 / 21

stopifnot() &
Assertions in R

Learn how to write defensive code that catches bugs early using stopifnot() and assert-style condition checks in R.

R Programming

What Is an Assertion?

An assertion is a statement in your code that declares something must be TRUE at a specific point. If the condition is false, the program immediately stops and tells you what went wrong.

✓ Condition TRUE
Code keeps running normally: nothing happens.
✕ Condition FALSE
Code stops immediately with an informative error message.

Why Assertions Matter

Bugs caused by bad inputs are some of the hardest to find. Without assertions, a function might silently return a wrong answer. Assertions catch problems at the source rather than letting errors propagate through your program.

Bad Input Function Runs Wrong Answer ✕ WITHOUT ASSERTIONS Bad Input stopifnot() CHECK Error: STOPPED ✓ WITH ASSERTIONS

Introducing stopifnot()

stopifnot() is R's built-in assertion function. You pass it one or more logical conditions. If any condition evaluates to FALSE, R throws an error and stops execution.

# Basic syntax stopifnot(condition1, condition2, ...)
Built-in
No packages needed: available in base R.
Multiple checks
Pass many conditions at once, separated by commas.
Vectorized
All elements of a vector must be TRUE for it to pass.

The Assertion Rule

stopifnot(expr) Evaluate expression ALL TRUE Invisible NULL returned TRUE ANY FALSE Error thrown, execution stops FALSE Code continues...

Named vs. Unnamed Conditions

Since R 4.0, you can give conditions names to produce clearer error messages. Compare these two styles:

# Unnamed: error shows the expression stopifnot(x > 0) # Error: \( x > 0 \) is not TRUE # Named: error shows your custom message stopifnot( "x must be positive" = x > 0 ) # Error: x must be positive
Unnamed
Quick to write. Error shows the raw condition: good for small scripts.
Named
Takes one extra step. Error shows a human-readable message: better for shared code.

stopifnot() vs. if/stop()

R offers two main ways to halt on bad conditions. Here is how they compare:

stopifnot() if (...) stop()
Lines of code 1 line 2-3 lines
Custom message Named args (R 4.0+) Full control
Multiple checks Comma-separated Separate blocks
Vector handling All elements must be TRUE Must use all() manually
Best for Quick guard clauses Complex conditions

How to Apply Assertions

1
Identify assumptions. What must be true about inputs for your function to work correctly?
2
Place assertions early. Put stopifnot() at the top of your function, before any computation.
3
Write the condition. Express each assumption as a logical expression that evaluates to TRUE or FALSE.
4
Add a name (optional). Give each condition a descriptive string label for better error messages.
5
Test with bad input. Deliberately pass invalid values to confirm the assertion fires.

Example 1: Basic Guard

A function that computes the square root should only accept non-negative numbers:

safe_sqrt <- function(x) { stopifnot( "x must be numeric" = is.numeric(x), "x must be non-negative" = x >= 0 ) sqrt(x) } safe_sqrt(9) # Returns 3 safe_sqrt(-4) # Error: x must be non-negative safe_sqrt("a") # Error: x must be numeric

Example 2: Vector Assertions

When the condition produces a vector of TRUE/FALSE values, stopifnot() requires every element to be TRUE:

check_scores <- function(scores) { stopifnot( "scores must be numeric" = is.numeric(scores), "all scores must be 0-100" = scores >= 0 & scores <= 100 ) mean(scores) } check_scores(c(85, 92, 78)) # Returns 85 check_scores(c(85, 105, 78)) # Error: all scores must be 0-100

Example 3: Data Frame Validation

Use assertions to validate a data frame before running an analysis:

analyze_students <- function(df) { stopifnot( "input must be a data frame" = is.data.frame(df), "must have 'name' column" = "name" %in% names(df), "must have 'grade' column" = "grade" %in% names(df), "must have at least 1 row" = nrow(df) > 0 ) # Safe to proceed with analysis summary(df$grade) }

Where to Place Assertions

FUNCTION BODY stopifnot(...) Validate inputs at the top 1
result \( \leftarrow \) computation(x)
Main logic runs safely 2 stopifnot(is.finite(result)) Optional: validate output 3 return(result)

What Can You Check?

Type
is.numeric(x)
is.character(s)
is.logical(flag)
Length
length(x) == 1
length(v) > 0
nrow(df) >= 10
Range
\( x > 0 \)
\( x \geq 0 \land x \leq 1 \)
is.finite(x)
Structure
"col" %in% names(df)
ncol(m) == 3
is.data.frame(df)

Using if/stop() for Complex Messages

When you need to include variable values in the error message, if (...) stop() gives you more control:

divide <- function(a, b) { if (!is.numeric(a) || !is.numeric(b)) { stop("Both a and b must be numeric") } if (b == 0) { stop(paste("Cannot divide", a, "by zero")) } a / b } divide(10, 0) # Error: Cannot divide 10 by zero

Common Mistakes

✕ Using == for vectors
Writing stopifnot(x == 5) when x is a vector checks each element. Use identical(x, 5) or \( \text{length}(x) = 1 \land x = 5 \) for scalar checks.
✕ Forgetting NA handling
stopifnot(\( x > 0 \)) fails if x contains NA because \( \text{NA} > 0 \) returns NA, not TRUE. Add !is.na(x) first.
✕ Assertions in production loops
Running stopifnot() inside a tight loop millions of times adds overhead. Use assertions for function entry points, not inner loops.

Summary Reference

Feature stopifnot() if/stop() warning()
Halts execution Yes Yes No
Custom message Named args Full control Full control
Multiple conditions Built-in Manual Manual
Vector-aware Yes Need all() Need all()
Use case Guard clauses Complex errors Non-fatal alerts

Question 1 of 5

What happens when all conditions inside stopifnot() evaluate to TRUE?

Question 2 of 5

Which of the following is the correct syntax for a named assertion in stopifnot()?

Question 3 of 5

Given \( x \leftarrow c(3, -1, 5) \), what does stopifnot(\( x > 0 \)) do?

Question 4 of 5

Where is the best place to put stopifnot() inside a function?

Question 5 of 5

What error will the student see?