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.

Intro

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:

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

  if (method == "factorial")
    factorial(n)
  else
    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 CamelCase or underscore_case. Therefore, checkmate offers all assert 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. Note that this is a feature only very few advanced users need and checkmate currently only provides a CamelCase variant.

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 this flavor.

Scalars

Vectors

Attributes

Choices and Subsets

Matrices, Arrays and Data Frame

Safe Coercion to integer

Other builtin

File IO:

In case you miss flexibility

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

Argument Checks for the Lazy

The following functions allow a special syntax to define argument checks using a special pattern. E.g., qassert(x, "I+") asserts that x is an integer vector with at least one element and no missing values. This provide a completely alternative mini-language (or style) how to perform argument checks. 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(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.

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

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))
print(mb)
## Unit: microseconds
##    expr   min     lq     mean median      uq     max neval cld
##    r(x) 8.042 9.0875 10.72052 9.6585 10.3425  44.178   100   b
##   cm(x) 2.910 3.3630  5.36001 3.6715  4.0715 110.016   100  a 
##  cmq(x) 1.923 2.2920  4.02359 2.5055  2.7825 150.299   100  a
autoplot(mb)

Benchmark 2: Assert that 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) 61.683 62.9650 70.66008 72.768 73.9885 113.562   100   c
##   cm(x)  8.956 10.2640 12.78828 10.638 11.3435 144.390   100  b 
##  cmq(x)  7.583  8.0255  8.70134  8.373  8.8070  20.716   100 a
autoplot(mb)

Benchmark 3: Assert that 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(nzchar(x)))
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) 57.067 57.9855 118.50928 62.2675 88.5245 4189.794   100   a
##   cm(x) 53.693 55.4845  60.96802 56.5025 58.0355  258.398   100   a
##  cmq(x) 66.680 67.5230  71.02695 67.9240 69.2465  119.077   100   a
autoplot(mb)

Benchmark 4: Assert that 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) 118.064 119.7595 194.27280 173.023 181.1630 3870.292   100   b
##   cm(x)  32.169  33.7650  39.61912  35.407  37.8015  286.655   100  a 
##  cmq(x)  23.456  24.1680  27.49783  25.330  26.8390   91.815   100  a
autoplot(mb)

# checkmate tries to stop as early as possible
x$a[1] = NA
mb = microbenchmark(r(x), cm(x), cmq(x))
print(mb)
## Unit: microseconds
##    expr    min       lq      mean   median       uq      max neval cld
##    r(x) 99.750 101.3815 168.87724 102.2965 120.6560 4577.733   100   b
##   cm(x)  7.171   8.6825  11.24215  10.1620  11.2700   59.987   100  a 
##  cmq(x)  1.189   1.5820   2.18340   1.8395   2.5115   14.059   100  a
autoplot(mb)

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. Include the provided header file checkmate.h. Unfortunately, the include is a bit tedious at the moment and you have to make sure to include the header only once. To work around this issue, write your own header file “include_checkmate.h” (see below for an example).
  3. In every file you want to use qtest or qassert, include checkmate.h or include_checkmate.h, respectively.
/* Examplary header file as workaround for (2) */
#ifndef INCLUDE_CHECKMATE_H_
#define INCLUDE_CHECKMATE_H_
#include <checkmate.h>
#endif
#include "include_checkmate.h"
/* alternative: #include <checkmate.h> */

SEXP double(SEXP x) {
  /* x must be a numeric, not NA and must have length 1 */
  qassert(x, "N1");

  num = REAL(x)[0];
  return ScalarReal(num * num);
}

Session Info

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

sessionInfo()
## R version 3.2.3 (2015-12-10)
## Platform: x86_64-apple-darwin13.4.0 (64-bit)
## Running under: OS X 10.11.2 (El Capitan)
## 
## locale:
## [1] de_DE.UTF-8/en_US.UTF-8/de_DE.UTF-8/C/de_DE.UTF-8/en_US.UTF-8
## 
## attached base packages:
## [1] methods   stats     graphics  grDevices utils     datasets  base     
## 
## other attached packages:
## [1] microbenchmark_1.4-2.1 ggplot2_2.0.0          checkmate_1.7         
## [4] rt_0.1                 nvimcom_0.9-8.2       
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_0.12.3      knitr_1.12.3     magrittr_1.5     splines_3.2.3   
##  [5] devtools_1.9.1   munsell_0.4.2    docopt_0.4.3.3   lattice_0.20-33 
##  [9] colorspace_1.2-6 multcomp_1.4-2   stringr_1.0.0    plyr_1.8.3      
## [13] tools_3.2.3      grid_3.2.3       data.table_1.9.6 gtable_0.1.2    
## [17] TH.data_1.0-6    htmltools_0.3    survival_2.38-3  yaml_2.1.13     
## [21] digest_0.6.9     crayon_1.3.1     formatR_1.2.1    codetools_0.2-14
## [25] memoise_0.2.1    evaluate_0.8     rmarkdown_0.9.2  sandwich_2.3-4  
## [29] stringi_1.0-1    scales_0.3.0     mvtnorm_1.0-4    chron_2.3-47    
## [33] zoo_1.7-12