01 / 20

Testing with
Edge Cases in R

Learn to design robust tests using boundary values, missing data, and unexpected inputs to write R code that never breaks in production.

R Programming

What Is an Edge Case?

An edge case is an input or scenario at the extreme boundary of what your function is designed to handle. These are the values most likely to reveal hidden bugs: empty vectors, \( \text{NA} \) values, very large numbers, or inputs of the wrong type.

Why Edge Cases Matter

✕ Silent Failures
R often returns \( \text{NA} \) or \( \text{numeric(0)} \) instead of throwing an error, hiding bugs deep in your analysis.
★ Real Data Is Messy
Datasets contain missing values, zero-length groups, and unexpected types that your functions must handle.
✓ Confidence
Thorough tests let you refactor fearlessly knowing edge cases are already covered.

The Testing Landscape in R

testthat expect_equal() expect_error() expect_warning() Boundary Values 0, Inf, -Inf Empty vectors Missing Data NA, NaN, NULL Partial NAs Type Errors Character vs Numeric Wrong dimensions

The Core Rule of Edge Case Testing

1
Identify inputs: What arguments does the function accept?
2
List extremes: Empty, \( \text{NA} \), \( \text{NULL} \), \( \text{Inf} \), negative, zero, very large.
3
Define expected behavior: Should the function return a value, throw an error, or return NA?
4
Write the test: Use expect_equal(), expect_error(), or expect_true() to assert the behavior.

Categories of Edge Cases

Boundary
\( \text{numeric(0)} \)
length-1 vector
\( \text{Inf, -Inf, 0} \)
\( \text{.Machine\$integer.max} \)
Missing Data
\( \text{NA} \)
\( \text{NaN} \)
\( \text{NULL} \)
\( \text{c(1, NA, 3)} \)
Type Mismatch "abc" for numeric list vs vector factor input matrix vs df Structural 0-row data frame 1-row data frame Mismatched lengths Logical All identical values
\( \text{All NAs} \)
Negative where + expected

NA vs NaN vs NULL

\( \text{NA} \) \( \text{NaN} \) \( \text{NULL} \)
Meaning Missing / unknown value Not a number (\( \frac{0}{0} \)) Absence of a value
\( \text{is.na()} \) returns \( \text{TRUE} \) \( \text{TRUE} \) \( \text{logical(0)} \)
\( \text{is.null()} \) returns \( \text{FALSE} \) \( \text{FALSE} \) \( \text{TRUE} \)
\( \text{length()} \) \( 1 \) \( 1 \) \( 0 \)
In a vector Keeps its slot Keeps its slot Silently dropped

Step-by-Step Testing Workflow

1
Write the function first. Start with the "happy path" that handles typical inputs correctly.
2
List all input parameters and their expected types (numeric vector, data frame, single integer, etc.).
3
Brainstorm edge cases for each parameter: empty, NA-filled, wrong type, single element, huge values.
4
Decide expected output for each: return NA? Throw an error? Return a default?
5
Write tests with testthat: one test_that() block per edge case category.
6
Run and iterate. Fix failures, add guards (stopifnot, if checks), re-run until all pass.

Example 1: safe_mean()

Let's write a function that computes the mean of a numeric vector but handles edge cases gracefully.

safe_mean <- function(x) { if (is.null(x) || length(x) == 0) return(NA_real_) if (!is.numeric(x)) stop("x must be numeric") mean(x, na.rm = TRUE) }

Testing safe_mean()

library(testthat) test_that("safe_mean handles normal input", { expect_equal(safe_mean(c(2, 4, 6)), 4) }) test_that("safe_mean handles edge cases", { expect_equal(safe_mean(c(1, NA, 3)), 2) expect_true(is.na(safe_mean(numeric(0)))) expect_true(is.na(safe_mean(NULL))) expect_error(safe_mean("hello")) })

Example 2: safe_divide()

A function that divides two numbers but handles division by zero and non-numeric inputs.

safe_divide <- function(a, b) { if (!is.numeric(a) || !is.numeric(b)) { stop("Both arguments must be numeric") } # Vectorized check: return NA where b is 0 or NA, otherwise a / b ifelse(b == 0 | is.na(b), NA_real_, a / b) }
test_that("safe_divide edge cases", { expect_equal(safe_divide(10, 2), 5) expect_true(is.na(safe_divide(10, 0))) expect_true(is.na(safe_divide(5, NA))) expect_length(safe_divide(10, numeric(0)), 0) expect_error(safe_divide("x", 2)) })

Example 3: Testing a Data Frame Function

get_top_n <- function(df, col, n = 5) { if (!is.data.frame(df)) stop("df must be a data frame") if (n < 0) stop("n cannot be negative") if (nrow(df) == 0) return(df) if (!col %in% names(df)) stop("Column not found") df[order(df[[col]], decreasing = TRUE), ][1:min(n, nrow(df)), ] }
test_that("get_top_n handles structural edges", { empty_df <- data.frame(x = numeric(0)) expect_equal(nrow(get_top_n(empty_df, "x")), 0) small_df <- data.frame(x = c(3, 1)) expect_equal(nrow(get_top_n(small_df, "x", 5)), 2) expect_error(get_top_n(small_df, "z")) expect_error(get_top_n(small_df, "x", n = -1)) expect_error(get_top_n("not_a_df", "x")) })

Key expect_*() Functions

Function What It Tests Edge Case Use
\( \text{expect\_equal(a, b)} \) a equals b (with tolerance) Normal output values
\( \text{expect\_true(x)} \) x is TRUE \( \text{is.na()} \), \( \text{is.null()} \) checks
\( \text{expect\_error(expr)} \) Expression throws an error Wrong type, missing column
\( \text{expect\_warning(expr)} \) Expression produces a warning Coercion warnings
\( \text{expect\_length(x, n)} \) \( \text{length(x) == n} \) Empty/single outputs
\( \text{expect\_type(x, type)} \) \( \text{typeof(x)} \) matches Return type consistency

Common Mistakes

✕ Testing Only Happy Path
Writing tests only for normal inputs and ignoring empty, NA, or wrong-type scenarios.
✕ Forgetting na.rm
Using \( \text{mean(x)} \) without \( \text{na.rm = TRUE} \) and not testing with NA inputs, so the function silently returns NA.
✕ Confusing NULL and NA
Checking \( \text{is.na(NULL)} \) returns \( \text{logical(0)} \), not \( \text{TRUE} \). Guard clauses must check \( \text{is.null()} \) separately.

Edge Case Cheat Sheet

Input Type Edge Case Test With
Numeric vector \( \text{numeric(0)} \), \( \text{c(NA)} \), \( \text{Inf} \) expect_true(is.na(...))
Character vector \( "" \), \( \text{character(0)} \) expect_length(..., 0)
Data frame 0-row, missing column expect_error(...)
Single value \( \text{NA} \), \( \text{NULL} \), \( \text{NaN} \) expect_true(is.na(...))
Integer \( 0 \), negative, \( \text{.Machine\$integer.max} \) expect_equal(...)
Any argument Wrong type passed expect_error(...)

Question 1 of 5

What does \( \text{mean(c(1, NA, 3))} \) return in R without setting \( \text{na.rm = TRUE} \)?

Question 2 of 5

Which testthat function should you use to verify that a function throws an error when given invalid input?

Question 3 of 5

What is the length of \( \text{NULL} \) in R?

Question 4 of 5

You write a function that accepts a numeric vector. Which of the following is NOT a useful edge case to test?

Question 5 of 5

What does \( \text{is.na(NaN)} \) return in R?