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 these 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 (is.na(n))
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")
factorial(n)
else
sqrt(2 * pi * n) * (n / exp(1))^n
}
```

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

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.

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`

:

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.

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.

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(testthat)
library(checkmate) # for testthat extensions
test_check("mypkg")
```

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

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.

`x`

is a flag```
library(checkmate)
library(ggplot2)
library(microbenchmark)
x = TRUE
r = function(x, na.ok = FALSE) { stopifnot(is.logical(x), length(x) == 1, na.ok || !is.na(x)) }
cm = function(x) assertFlag(x)
cmq = function(x) qassert(x, "B1")
mb = microbenchmark(r(x), cm(x), cmq(x))
```

```
## Warning in microbenchmark(r(x), cm(x), cmq(x)): less accurate nanosecond times
## to avoid potential integer overflows
```

```
## Unit: nanoseconds
## expr min lq mean median uq max neval cld
## r(x) 1681 1763 16261.42 1804 1947.5 1417575 100 a
## cm(x) 1148 1189 5058.17 1230 1332.5 318816 100 a
## cmq(x) 697 779 4801.51 779 861.0 343211 100 a
```

`x`

is a numeric of length 1000
with no missing nor NaN values```
x = runif(1000)
r = function(x) stopifnot(is.numeric(x), length(x) == 1000, all(!is.na(x) & x >= 0 & x <= 1))
cm = function(x) assertNumeric(x, len = 1000, any.missing = FALSE, lower = 0, upper = 1)
cmq = function(x) qassert(x, "N1000[0,1]")
mb = microbenchmark(r(x), cm(x), cmq(x))
print(mb)
```

```
## Unit: microseconds
## expr min lq mean median uq max neval cld
## r(x) 9.594 10.045 25.59630 10.168 10.291 1534.917 100 a
## cm(x) 3.403 3.526 7.96343 3.608 3.690 365.474 100 a
## cmq(x) 2.911 2.993 6.20699 3.034 3.116 308.279 100 a
```

`x`

is a character vector with
no missing values nor empty strings```
x = sample(letters, 10000, replace = TRUE)
r = function(x) stopifnot(is.character(x), !any(is.na(x)), all(nchar(x) > 0))
cm = function(x) assertCharacter(x, any.missing = FALSE, min.chars = 1)
cmq = function(x) qassert(x, "S+[1,]")
mb = microbenchmark(r(x), cm(x), cmq(x))
print(mb)
```

```
## Unit: microseconds
## expr min lq mean median uq max neval cld
## r(x) 135.833 144.648 157.28994 145.755 147.887 1185.515 100 a
## cm(x) 133.127 133.496 139.99286 133.660 133.865 609.342 100 a
## cmq(x) 58.876 58.958 63.29252 59.081 61.787 373.633 100 b
```

`x`

is a data frame with no
missing values```
N = 10000
x = data.frame(a = runif(N), b = sample(letters[1:5], N, replace = TRUE), c = sample(c(FALSE, TRUE), N, replace = TRUE))
r = function(x) is.data.frame(x) && !any(sapply(x, function(x) any(is.na(x))))
cm = function(x) testDataFrame(x, any.missing = FALSE)
cmq = function(x) qtest(x, "D")
mb = microbenchmark(r(x), cm(x), cmq(x))
print(mb)
```

```
## Unit: microseconds
## expr min lq mean median uq max neval cld
## r(x) 57.728 66.256 80.08735 67.035 69.1875 1198.635 100 a
## cm(x) 22.714 23.042 27.41137 23.124 23.2880 341.571 100 b
## cmq(x) 18.860 18.901 23.71071 18.983 19.0650 454.321 100 b
```

```
# checkmate tries to stop as early as possible
x$a[1] = NA
mb = microbenchmark(r(x), cm(x), cmq(x))
print(mb)
```

```
## Unit: nanoseconds
## expr min lq mean median uq max neval cld
## r(x) 55186 56149.5 58493.88 56969.5 58855.5 107584 100 a
## cm(x) 3034 3218.5 3608.82 3362.0 3587.5 12382 100 b
## cmq(x) 451 492.0 665.84 553.5 656.0 9102 100 c
```

`x`

is an increasing sequence of
integers with no missing values```
N = 10000
x.altrep = seq_len(N) # this is an ALTREP in R version >= 3.5.0
x.sexp = c(x.altrep) # this is a regular SEXP OTOH
r = function(x) stopifnot(is.integer(x), !any(is.na(x)), !is.unsorted(x))
cm = function(x) assertInteger(x, any.missing = FALSE, sorted = TRUE)
mb = microbenchmark(r(x.sexp), cm(x.sexp), r(x.altrep), cm(x.altrep))
print(mb)
```

```
## Unit: microseconds
## expr min lq mean median uq max neval cld
## r(x.sexp) 25.953 29.0075 29.96690 29.397 30.0530 66.748 100 ab
## cm(x.sexp) 11.029 11.5415 11.77110 11.767 12.0130 13.120 100 b
## r(x.altrep) 29.602 31.4265 44.71337 32.103 32.7590 1247.794 100 a
## cm(x.altrep) 1.804 1.9270 6.73220 2.091 2.2345 397.577 100 b
```

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))
return(res)
if (nrow(x) != ncol(x))
return("Must be square")
return(TRUE)
}
# a quick test:
X = matrix(1:9, nrow = 3)
checkSquareMatrix(X)
```

`## [1] TRUE`

`## [1] "Must store characters"`

`## [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)
print(assertSquareMatrix)
```

```
## function (x, mode = NULL, .var.name = checkmate::vname(x), add = NULL)
## {
## if (missing(x))
## stop(sprintf("argument \"%s\" is missing, with no default",
## .var.name))
## res = checkSquareMatrix(x, mode)
## checkmate::makeAssertion(x, res, .var.name, add)
## }
```

```
# For tests:
test_square_matrix = testSquareMatrix = makeTestFunction(checkSquareMatrix)
print(testSquareMatrix)
```

```
## function (x, mode = NULL)
## {
## isTRUE(checkSquareMatrix(x, mode))
## }
```

```
# For expectations:
expect_square_matrix = makeExpectationFunction(checkSquareMatrix)
print(expect_square_matrix)
```

```
## 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 `.var.name`

,
`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).

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

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:

- Add
`checkmate`

to your “Imports” and “LinkingTo” sections in your DESCRIPTION file. - Create a stub C source file
`"checkmate_stub.c"`

, see below. - Include the provided header file
`<checkmate.h>`

in each compilation unit where you want to use checkmate.

File contents for (2):

For the sake of completeness, here the `sessionInfo()`

for
the benchmark (but remember the note before on `knitr`

possibly biasing the results).

```
## R version 4.3.1 (2023-06-16)
## Platform: aarch64-apple-darwin20 (64-bit)
## Running under: macOS Sonoma 14.0
##
## Matrix products: default
## BLAS: /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/lib/libRlapack.dylib; LAPACK version 3.11.0
##
## locale:
## [1] C/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
##
## time zone: Europe/Berlin
## tzcode source: internal
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] microbenchmark_1.4.10 ggplot2_3.4.4 checkmate_2.3.0
##
## loaded via a namespace (and not attached):
## [1] Matrix_1.6-1.1 gtable_0.3.4 jsonlite_1.8.7 dplyr_1.1.3
## [5] compiler_4.3.1 tidyselect_1.2.0 jquerylib_0.1.4 splines_4.3.1
## [9] scales_1.2.1 yaml_2.3.7 fastmap_1.1.1 TH.data_1.1-2
## [13] lattice_0.21-8 R6_2.5.1 generics_0.1.3 knitr_1.44
## [17] MASS_7.3-59 backports_1.4.1 tibble_3.2.1 munsell_0.5.0
## [21] bslib_0.5.1 pillar_1.9.0 rlang_1.1.1 utf8_1.2.4
## [25] multcomp_1.4-25 cachem_1.0.8 xfun_0.40 sass_0.4.7
## [29] cli_3.6.1 withr_2.5.1 magrittr_2.0.3 digest_0.6.33
## [33] grid_4.3.1 mvtnorm_1.2-3 sandwich_3.0-2 lifecycle_1.0.3
## [37] vctrs_0.6.4 evaluate_0.22 glue_1.6.2 farver_2.1.1
## [41] codetools_0.2-19 zoo_1.8-12 survival_3.5-5 fansi_1.0.5
## [45] colorspace_2.1-0 rmarkdown_2.25 tools_4.3.1 pkgconfig_2.0.3
## [49] htmltools_0.5.6.1
```