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 flaglibrary(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) 2296 2337 16416.40 2378 2460 1390105 100 a
## cm(x) 1558 1599 6275.46 1640 1722 403645 100 a
## cmq(x) 984 1025 7812.55 1066 1148 612663 100 a
x is a numeric of length 1000
with no missing nor NaN valuesx = 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) 12.710 13.038 32.76064 13.202 13.325 1942.498 100 a
## cm(x) 4.674 4.797 10.48124 4.879 4.961 494.050 100 a
## cmq(x) 3.936 4.018 9.92774 4.059 4.141 575.353 100 a