:eyes: assert
assert provides a replacement to stopifnot
and
assertthat::assert_that
which provides more informative error
messages.
Installation
You can install the released version of assert from CRAN with:
install.packages("assert")
And the development version from GitHub with:
# install.packages("devtools")
devtools::install_github("OlivierBinette/assert")
Examples
Assertions throughout a data analysis workflow:
library(assert)
attach(ChickWeight)
# Passing assertions
assert(is.numeric(weight),
all(weight > 0))
# Failing assertions
assert(all(Diet > 0),
is.numeric(Times))
#> Error in assert(all(Diet > 0), is.numeric(Times)) :
#> Failed checks:
#> all(Diet > 0) (NA)
#> is.numeric(Times) (object 'Times' not found)
Validate function arguments:
# Sample from a multivariate normal distribution
rmultinorm <- function(k, mu, sigma) {
assert(is.numeric(k),
length(k) == 1,
k > 0,
msg = "Number of samples `k` should be a positive integer")
assert(is.numeric(mu),
is.matrix(sigma),
all(length(mu) == dim(sigma)),
msg = "Mean vector should match the covariance matrix dimensions.")
p <- length(mu)
t(chol(sigma)) %*% matrix(rnorm(p*k, 0, 1), nrow=p) + mu
}
mu <- c(0,10)
sigma <- matrix(c(2,1,1,2), nrow=2)
rmultinorm(3, mu, sigma)
#> [,1] [,2] [,3]
#> [1,] 0.111465 -1.193094 0.4347379
#> [2,] 10.037030 8.237249 8.2379180
rmultinorm(mu, 3, sigma)
#> Error: in rmultinorm(k = mu, mu = 3, sigma = sigma)
#> Failed checks:
#> length(k) == 1
#> k > 0 (c(FALSE, TRUE))
#>
#> Number of samples `k` should be a positive integer