Skip to content

Instantly share code, notes, and snippets.

@OlivierBinette OlivierBinette/assert.R
Last active Nov 20, 2019

Embed
What would you like to do?
[Assert] Argument checking function #R
assert <- function(..., msg=NULL) {
# Assert that each of the provided expression is true. Otherwise returns a
# description of each failed assertion.
#
# Args:
# ...: List of logical assertions
# msg: Optional parameter printed when one of the assertions fails.
#
# Returns:
# Nothing if all assertions pass. Otherwise throws an error describing which
# assertions failed.
#
# Examples:
# > assert(2 < 1, 1 == 1, "1" == 2)
# ## Error in assert(2 < 1, 1 == 1, "1" == 2) : Failed checks:
# ## 2 < 1
# ## "1" == 2
#
# # In a function to validate arguments:
# > sum <- function(a, b) {
# > assert(is.numeric(a),
# > is.numeric(b),
# > length(a) == length(b))
# > return(a+b)
# > }
# > sum("1", 2)
# ## Error: in sum(a = "1", b = c(1, 2))
# ## Failed checks:
# ## is.numeric(a)
# ## length(a) == length(b)
#
r = c(...)
if (any(!r)) {
fails = paste0(substitute(c(...)))[-1][!r]
if(identical(parent.frame(), globalenv())) {
stop(c("Failed checks: \n\t",
paste(fails, "\n\t"),
"\n", msg))
} else {
msg = c("in ",
eval(quote(match.call()), parent.frame()),
"\n",
"Failed checks: \n\t",
paste(fails, "\n\t"),
"\n", msg)
stop(msg, call. = FALSE)
}
}
}
sum <- function(a, b) {
assert(is.numeric(a), is.numeric(b))
assert(length(a) == length(b))
return(a+b)
}
sum("1", c(1,2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.