Michel Lang


Ever used an R function that produced a not-very-helpful error message, just to discover after minutes of debugging that you simply passed a wrong argument?

Blaming the laziness of the package author for not doing such standard checks (in a dynamically typed language such as R) is at least partially unfair, as R makes theses types of checks cumbersome and annoying. Well, that’s how it was in the past.

Enter checkmate.

Virtually every standard type of user error when passing arguments into function can be caught with a simple, readable line which produces an informative error message in case. A substantial part of the package was written in C to minimize any worries about execution time overhead.


As a motivational example, consider you have a function to calculate the faculty of a natural number and the user may choose between using either the stirling approximation or R’s factorial function (which internally uses the gamma function). Thus, you have two arguments, n and method. Argument n must obviously be a positive natural number and method must be either "stirling" or "factorial". Here is a version of all the hoops you need to jump through to ensure that these simple requirements are met:

fact <- function(n, method = "stirling") {
  if (length(n) != 1)
    stop("Argument 'n' must have length 1")
  if (!is.numeric(n))
    stop("Argument 'n' must be numeric")
  if (
    stop("Argument 'n' may not be NA")
  if (is.double(n)) {
    if (is.nan(n))
      stop("Argument 'n' may not be NaN")
    if (is.infinite(n))
      stop("Argument 'n' must be finite")
    if (abs(n - round(n, 0)) > sqrt(.Machine$double.eps))
      stop("Argument 'n' must be an integerish value")
    n <- as.integer(n)
  if (n < 0)
    stop("Argument 'n' must be >= 0")
  if (length(method) != 1)
    stop("Argument 'method' must have length 1")
  if (!is.character(method) || !method %in% c("stirling", "factorial"))
    stop("Argument 'method' must be either 'stirling' or 'factorial'")

  if (method == "factorial")
    sqrt(2 * pi * n) * (n / exp(1))^n

And for comparison, here is the same function using checkmate:

fact <- function(n, method = "stirling") {
  assertChoice(method, c("stirling", "factorial"))

  if (method == "factorial")
    sqrt(2 * pi * n) * (n / exp(1))^n

Function overview

The functions can be split into four functional groups, indicated by their prefix.

If prefixed with assert, an error is thrown if the corresponding check fails. Otherwise, the checked object is returned invisibly. There are many different coding styles out there in the wild, but most R programmers stick to either camelBack or underscore_case. Therefore, checkmate offers all functions in both flavors: assert_count is just an alias for assertCount but allows you to retain your favorite style.

The family of functions prefixed with test always return the check result as logical value. Again, you can use test_count and testCount interchangeably.

Functions starting with check return the error message as a string (or TRUE otherwise) and can be used if you need more control and, e.g., want to grep on the returned error message.

expect is the last family of functions and is intended to be used with the testthat package. All performed checks are logged into the testthat reporter. Because testthat uses the underscore_case, the extension functions only come in the underscore style.

All functions are categorized into objects to check on the package help page.

In case you miss flexibility

You can use assert to perform multiple checks at once and throw an assertion if all checks fail.

Here is an example where we check that x is either of class foo or class bar:

f <- function(x) {
    checkClass(x, "foo"),
    checkClass(x, "bar")

Note that assert(, combine = "or") and assert(, combine = "and") allow to control the logical combination of the specified checks, and that the former is the default.

Argument Checks for the Lazy

The following functions allow a special syntax to define argument checks using a special format specification. E.g., qassert(x, "I+") asserts that x is an integer vector with at least one element and no missing values. This very simple domain specific language covers a large variety of frequent argument checks with only a few keystrokes. You choose what you like best.

checkmate as testthat extension

To extend testthat, you need to IMPORT, DEPEND or SUGGEST on the checkmate package. Here is a minimal example:

# file: tests/test-all.R
library(checkmate) # for testthat extensions

Now you are all set and can use more than 30 new expectations in your tests.

test_that("checkmate is a sweet extension for testthat", {
  x = runif(100)
  expect_numeric(x, len = 100, any.missing = FALSE, lower = 0, upper = 1)
  # or, equivalent, using the lazy style:
  qexpect(x, "N100[0,1]")

Speed considerations

In comparison with tediously writing the checks yourself in R (c.f. factorial example at the beginning of the vignette), R is sometimes a tad faster while performing checks on scalars. This seems odd at first, because checkmate is mostly written in C and should be comparably fast. Yet many of the functions in the base package are not regular functions, but primitives. While primitives jump directly into the C code, checkmate has to use the considerably slower .Call interface. As a result, it is possible to write (very simple) checks using only the base functions which, under some circumstances, slightly outperform checkmate. However, if you go one step further and wrap the custom check into a function to convenient re-use it, the performance gain is often lost (see benchmark 1).

For larger objects the tide has turned because checkmate avoids many unnecessary intermediate variables. Also note that the quick/lazy implementation in qassert/qtest/qexpect is often a tad faster because only two arguments have to be evaluated (the object and the rule) to determine the set of checks to perform.

Below you find some (probably unrepresentative) benchmark. But also note that this one here has been executed from inside knitr which is often the cause for outliers in the measured execution time. Better run the benchmark yourself to get unbiased results.

Benchmark 1: Assert that x is a flag

## Unit: microseconds
##    expr    min      lq     mean  median      uq      max neval
##    r(x) 34.100 35.7750 71.35144 36.2065 36.8215 3477.414   100
##   cm(x)  2.754  3.2005 16.86151  3.4265  3.6560 1202.327   100
##  cmq(x)  2.020  2.2410 16.90276  2.5825  2.8680 1330.526   100
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.

Benchmark 2: Assert that x is a numeric of length 1000 with no missing nor NaN values

## Unit: microseconds
##    expr    min      lq      mean median      uq      max neval
##    r(x) 51.834 59.5775 121.21002 60.533 62.0590 5949.569   100
##   cm(x)  7.029  8.0135  25.48076  8.631  9.5120 1437.352   100
##  cmq(x)  8.140  9.2535  32.14792  9.695 10.3815 2169.813   100
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.

Benchmark 3: Assert that x is a character vector with no missing values nor empty strings

## Unit: microseconds
##    expr      min        lq      mean   median       uq      max neval
##    r(x) 1717.864 1772.0325 1866.9911 1788.226 1825.924 5105.189   100
##   cm(x)  117.743  119.9805  143.8170  123.355  129.399 1480.445   100
##  cmq(x)  133.462  136.1815  153.9877  141.288  144.665 1195.723   100
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.

Benchmark 4: Test that x is a data frame with no missing values

## Unit: microseconds
##    expr     min      lq      mean   median       uq      max neval
##    r(x) 178.898 184.334 236.81761 191.2360 199.6105 4223.329   100
##   cm(x)  25.656  26.684  42.99187  28.4890  29.7210 1134.436   100
##  cmq(x)  17.098  17.818  29.50008  18.7425  19.6075 1040.400   100
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.

## Unit: microseconds
##    expr     min       lq      mean   median       uq     max neval
##    r(x) 126.419 167.3140 183.53572 173.6855 186.2875 265.165   100
##   cm(x)   6.480   7.4060   9.55978   9.6645  10.5200  31.350   100
##  cmq(x)   1.158   1.5145   2.43574   2.0300   3.0180  19.371   100
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.

Benchmark 5: Assert that x is an increasing sequence of integers with no missing values

## Unit: microseconds
##          expr     min       lq      mean   median       uq      max neval
##     r(x.sexp)  93.914 123.2420 171.91943 125.2220 136.4130 3361.278   100
##    cm(x.sexp)  19.543  20.4210  24.88823  22.9725  23.8495   59.140   100
##   r(x.altrep) 115.601 148.7020 167.23889 151.4205 160.5720  411.929   100
##  cm(x.altrep)   4.666   5.5155  21.73968   8.0425   9.0600 1294.410   100
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.

Extending checkmate

To extend checkmate a custom check* function has to be written. For example, to check for a square matrix one can re-use parts of checkmate and extend the check with additional functionality:

checkSquareMatrix = function(x, mode = NULL) {
  # check functions must return TRUE on success
  # and a custom error message otherwise
  res = checkMatrix(x, mode = mode)
  if (!isTRUE(res))
  if (nrow(x) != ncol(x))
    return("Must be square")

# a quick test:
X = matrix(1:9, nrow = 3)
## [1] TRUE
checkSquareMatrix(X, mode = "character")
## [1] "Must store characters"
checkSquareMatrix(X[1:2, ])
## [1] "Must be square"

The respective counterparts to the check-function can be created using the constructors makeAssertionFunction, makeTestFunction and makeExpectationFunction:

# For assertions:
assert_square_matrix = assertSquareMatrix = makeAssertionFunction(checkSquareMatrix)
## function (x, mode = NULL, = checkmate::vname(x), add = NULL) 
## {
##     if (missing(x)) 
##         stop(sprintf("argument \"%s\" is missing, with no default", 
##     res = checkSquareMatrix(x, mode)
##     checkmate::makeAssertion(x, res,, add)
## }
# For tests:
test_square_matrix = testSquareMatrix = makeTestFunction(checkSquareMatrix)
## function (x, mode = NULL) 
## {
##     isTRUE(checkSquareMatrix(x, mode))
## }
# For expectations:
expect_square_matrix = makeExpectationFunction(checkSquareMatrix)
## function (x, mode = NULL, info = NULL, label = vname(x)) 
## {
##     if (missing(x)) 
##         stop(sprintf("Argument '%s' is missing", label))
##     res = checkSquareMatrix(x, mode)
##     makeExpectation(x, res, info, label)
## }

Note that all the additional arguments, add, info and label are automatically joined with the function arguments of your custom check function. Also note that if you define these functions inside an R package, the constructors are called at build-time (thus, there is no negative impact on the runtime).

Calling checkmate from C/C++

The package registers two functions which can be used in other packages’ C/C++ code for argument checks.

SEXP qassert(SEXP x, const char *rule, const char *name);
Rboolean qtest(SEXP x, const char *rule);

These are the counterparts to qassert and qtest. Due to their simplistic interface, they perfectly suit the requirements of most type checks in C/C++.

For detailed background information on the register mechanism, see the Exporting C Code section in Hadley’s Book “R Packages” or WRE. Here is a step-by-step guide to get you started:

  1. Add checkmate to your “Imports” and “LinkingTo” sections in your DESCRIPTION file.
  2. Create a stub C source file "checkmate_stub.c", see below.
  3. Include the provided header file <checkmate.h> in each compilation unit where you want to use checkmate.

File contents for (2):

#include <checkmate.h>
#include <checkmate_stub.c>

Session Info

For the sake of completeness, here the sessionInfo() for the benchmark (but remember the note before on knitr possibly biasing the results).

## R version 3.5.3 (2019-03-11)
## Platform: x86_64-apple-darwin15.6.0 (64-bit)
## Running under: macOS Mojave 10.14.4
## Matrix products: default
## BLAS: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib
## locale:
## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## other attached packages:
## [1] microbenchmark_1.4-6 ggplot2_3.1.1        checkmate_1.9.3     
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.1       knitr_1.22       magrittr_1.5     munsell_0.5.0   
##  [5] colorspace_1.4-1 rlang_0.3.4      stringr_1.4.0    plyr_1.8.4      
##  [9] tools_3.5.3      grid_3.5.3       gtable_0.3.0     xfun_0.6        
## [13] withr_2.1.2      htmltools_0.3.6  yaml_2.2.0       lazyeval_0.2.2  
## [17] digest_0.6.18    tibble_2.1.1     crayon_1.3.4     evaluate_0.13   
## [21] rmarkdown_1.12   stringi_1.4.3    compiler_3.5.3   pillar_1.3.1    
## [25] scales_1.0.0     backports_1.1.4  pkgconfig_2.0.2