Skip to content

Instantly share code, notes, and snippets.

@OlivierBinette
Last active September 29, 2021 00:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OlivierBinette/a048d7c1f470740b64e95c74828c8516 to your computer and use it in GitHub Desktop.
Save OlivierBinette/a048d7c1f470740b64e95c74828c8516 to your computer and use it in GitHub Desktop.
[Assert] Validate function arguments #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