Skip to content

Instantly share code, notes, and snippets.

@leeper
Created March 1, 2016 15:41
Show Gist options
  • Save leeper/2ef8c816a6e3d8e39b23 to your computer and use it in GitHub Desktop.
Save leeper/2ef8c816a6e3d8e39b23 to your computer and use it in GitHub Desktop.
Assertion framework for checking recodings
# relevant to recoding: https://gist.github.com/leeper/c669fd4a6dcb9ac23612
# assertion function
assert <- function(x, length, class, min, max, has, excludes, of, miss) {
if (!missing(length)) {
stopifnot(length(x) == length)
}
if (!missing(class)) {
stopifnot(inherits(x, as.character(substitute(class))))
}
if (!missing(min)) {
stopifnot(min(x, na.rm = TRUE) == min)
}
if (!missing(max)) {
stopifnot(max(x, na.rm = TRUE) == max)
}
if (!missing(has)) {
stopifnot(all(has %in% x))
}
if (!missing(excludes)) {
stopifnot(any(!x %in% excludes))
}
if (!missing(of)) {
stopifnot(all(x %in% of))
}
if (!missing(miss)) {
if (is.logical(miss)) {
if (miss) {
stopifnot(any(is.na(x)))
} else {
stopifnot(!any(is.na(x)))
}
} else {
stopifnot(any(!which(is.na(x)) %in% miss))
}
}
x
}
x <- 1:3
assert(x, of = 1:4)
assert(x, length = 3, miss = FALSE)
assert(c(x, NA), class = "integer", min = 1, max = 3, miss = TRUE)
assert(letters[1:4], class = "character", has = "a", miss = FALSE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment