assertthat
assertthat copied to clipboard
Feature request: is.binary
Hi, I think it would be useful to have also an assertion for binary variables (0/1 indicators), since they quite often appear in statistics and data analysis.
Possible solution:
is.binary <- function(x, na.rm = TRUE) {
if (na.rm) x <- x[!is.na(x)]
is.numeric(x) && all(unique(x) %in% c(0, 1))
}
on_failure(is.binary) <- function(call, env) {
type <- eval(call$type, env)
paste0(deparse(call$x), " is not a binary vector (a numeric vector consisting only of 0's and 1's)."
}