Easy Pre and Post Assertions

An extension to stopifnot() that makes it easy to declare the pre and post conditions that you code should satisfy, while also producing friendly error messages so that your users know what's gone wrong.

Travis-CI Build Status

assertthat provides a drop in replacement for stopifnot() that makes it easy to check the pre- and post-conditions of a function, while producing useful error messages.

x <- 1:10
# Error: is.character(x) is not TRUE
# Error: x is not a character vector
assert_that(length(x) == 5)
# Error: length(x) not equal to 5
# [1] TRUE

This is a good defensive programming technique, and is useful as source-code documentation: you can see exactly what your function expects when you come back to it in the future. It is partly a response to the lack of static typing in R, but it allows you to test for general conditions (like length(x) == length(y)) that are difficult to express in a type system.

assertthat can be installed either from CRAN:


or with devtools:


New assertions

As well as all the functions provided by R, assertthat provides a few more that I use a lot:

  • is.flag(x): is x TRUE or FALSE? (a boolean flag)
  • is.string(x): is x a length 1 character vector?
  • has_name(x, nm), x %has_name% nm: does x have component nm?
  • has_attr(x, attr), x %has_attr% attr: does x have attribute attr?
  • is.count(x): is x a single positive integer?
  • are_equal(x, y): are x and y equal?
  • not_empty(x): are all dimensions of x greater than 0?
  • noNA(x): is x free from missing values?
  • is.dir(path): is path a directory?
  • is.writeable(path)/is.readable(path): is path writeable/readable?
  • has_extension(path, extension): does file have given extension?

assert_that, see_if and validate_that

There are three main functions in assertthat:

  • assert_that() signal an error

  • see_if() returns a logical value, with the error message as an attribute.

  • validate_that() returns TRUE on success, otherwise returns the error as a string.

You'll use assert_that() in your own code, but you'll mostly see see_if() in the examples (because R CMD check requires that examples run without errors). Use validate_that() for S4 validate methods.

Writing your own assertions

If you're writing your own assertions, you can provide custom error messages using the on_failure() helper:

is_odd <- function(x) {
  assert_that(is.numeric(x), length(x) == 1)
  x %% 2 == 1
# Error: is_odd(x = 2) is not TRUE
on_failure(is_odd) <- function(call, env) {
  paste0(deparse(call$x), " is even")
# Error: 2 is even

The on_failure callback is called with two arguments, the unevaluated function call (which has already been standardised with match.call()), and env, and the environment in which the assertion was executed. This allows you to choose between displaying values or names in your error messages. Read the advanced R book to learn more about working with calls.

Also note the use of assert_that() in our new function: assertions flow through function calls ensuring that you get a useful error message at the top level:

# Error: x is not a numeric or integer vector
# Error: length(x) not equal to 1


Reference manual

It appears you don't have a PDF plugin for this browser. You can click here to download the reference manual.


0.2.1 by Hadley Wickham, 3 years ago

Browse source code at https://github.com/cran/assertthat

Authors: Hadley Wickham [aut, cre]

Documentation:   PDF Manual  

GPL-3 license

Imports tools

Suggests testthat, covr

Imported by AntWeb, AzureAppInsights, Bioi, CAISEr, CALANGO, CausalImpact, DGEobj, DGEobj.utils, DIDmultiplegt, DataPackageR, DataSpaceR, ExpDE, FastKNN, FitUltD, GillespieSSA2, GlmSimulatoR, HARtools, IOHexperimenter, MODIStsp, MOEADr, NetworkInference, OncoBayes2, RAhrefs, RBesT, RClimacell, Rwtss, RxODE, SimplifyStats, TexExamRandomizer, TidyMultiqc, Tplyr, XKCDdata, adobeanalyticsr, aemo, afmToolkit, aglm, altair, ambiorix, anndata, antaresEditObject, antaresViz, arrow, auk, basecamb, bayefdr, beam, bigQueryR, bigdist, bigrquery, binman, bioRad, bnclassify, bnviewer, boxr, breathtestcore, cat2cat, chillR, cicerone, circumplex, clinspacy, clustringr, cms, cmsafops, cmsafvis, codyn, conogive, cvCovEst, d3po, dash, dataonderivatives, dbplyr, decisionSupport, delayed, diceR, disto, dkanr, dyngen, dynparam, dynplot, dynutils, dynwrap, easypackages, ech, eemR, einet, eph, explore, extendedFamily, fairadapt, fbar, fcci, ffp, fiery, flexsurv, flintyR, fmbasics, fmdates, foieGras, frenchdata, fuzzr, galah, ganalytics, gastempt, geouy, ggPMX, ggloop, ggsom, ggvis, gistr, git2rdata, glmmfields, glmtrans, googleAnalyticsR, googleAuthR, googleCloudRunner, googleCloudStorageR, googleComputeEngineR, googleLanguageR, googleTagManageR, grattan, greekLetters, gwer, hal9001, haldensify, heatmaply, highcharter, holodeck, humanize, huxtable, implyr, install.load, kdensity, keyring, latrend, lifx, lime, listWithDefaults, liteq, lmds, luzlogr, mRpostman, managelocalrepo, mapaccuracy, mashr, matsbyname, mcglm, mcvis, measurementProtocol, meteospain, miceFast, miniCRAN, mizer, mknapsack, moexer, mosqcontrol, mrgsim.sa, nakagami, nandb, nanostringr, neuroim, nima, nlpred, noah, nodeSub, oppr, origami, osrmr, packer, pak, paramlink, percentiles, pharmaRTF, pkgcache, pkgcond, pkgmaker, pkgnet, pkgsearch, pomcheckr, prcbench, precrec, prt, pspline.inference, ptvapi, pubtatordb, pushoverr, qrcode, qtl2ggplot, qtl2pattern, qualpalr, qualtRics, r511, raptr, ratelimitr, rayrender, rchess, rebird, regions, regmedint, remindR, reqres, retroharmonize, reutils, rfisheries, rgoogleslides, rhub, ricu, rmake, rmapzen, rmdfiltr, rnr, rotl, routr, rpcdsearch, rprime, rrd, rtsVis, rtypeform, rvinecopulib, rvmethod, saeRobust, safer, salty, santoku, sapfluxnetr, scUtils, secret, semver, seqgendiff, shinytest, slimrec, sortable, sparklyr, spotifyr, spreadr, spsComps, spsUtil, sss, staplr, superml, surveydata, tabulator, tatoo, tensr, testthis, textreuse, thinkr, tibbletime, tidydice, tidyjson, tidyrules, timetk, togglr, tricolore, txshift, uncorbets, univariateML, unstruwwel, updog, uptasticsearch, urlshorteneR, useful, varitas, vegawidget, vembedr, viafr, vinereg, wdman, wdpar, wordbankr, xgxr, ztype.

Depended on by bulletcp, condusco, sourceR.

Suggested by checkr, immunarch, lhs, povcalnetR, reproducer, rnassqs, themetagenomics.

See at CRAN