R/is_onezero.R

Defines functions is_onezero

Documented in is_onezero

#' 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)

}
ttrodrigz/onezero documentation built on May 9, 2023, 2:59 p.m.