#' Checks if a vector contains all 1/0s
#'
#' Checks to see if the vector is numeric and contains only ones and zeros, or
#' if the vector of class logical. Missing values are permitted.
#'
#' @seealso [onezero::onezero()]
#'
#' @param x A vector.
#'
#' @return `TRUE` or `FALSE`
#'
#' @examples
#'
#' is_onezero(c(1, 0, NA))
#' is_onezero(c(1, 0, -1))
#' is_onezero(c(TRUE, FALSE, FALSE))
#'
#' @export
is_onezero <- function(x) {
# logical vectors immediately pass
if (is.logical(x)) {
return(TRUE)
}
# if not logical, must be numeric
if (!is.numeric(x)) {
return(FALSE)
}
# if numeric, must contain only 1s, 0s (and NAs)
accept <- c(1, 0, NA)
all(x %in% accept)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.