R/make_logical.R

#' Convert a vector to logical
#'
#' \code{make_logical} will check with \code{hides_logical} that it is posible to coerce
#' to logical, then the given \code{true}  and \code{false} parameter will guide how to convert it.
#' Values enumerated in \code{na.values} will be converted to \code{NA} so it's not necessarily
#' required to pass a completely binary input
#'
#' @param x A vector.
#' @param true The value to set to \code{TRUE}, if not given, will guess.
#' @param false The value to set to \code{FALSE}, if not given, will guess.
#' @param na.values Values to set as \code{NA}.
#'
#' @export
#'
#' @examples
# make_logical(c(0,1,2,1,2,0), na.values = 0)
# # it's not safe not to mention the true and false values, here yes becomes FALSE
#
# make_logical(c("yes","no","yes","maybe"), na.values = "maybe")
# # we can mention only one of the true/false values
# make_logical(c("yes","no","yes","maybe"), false = "no",na.values = "maybe")
# # no message is displayed if both true/false values are given
# make_logical(c("yes","no","yes","maybe"), true = "yes", false = "no",na.values = "maybe")
make_logical <- function(x, true = NULL, false = NULL, na.values = NULL){
  if (!is.character(x)) x <- as.character(x)
  if (!hides_lgl(x,na.values))          stop("Inappropriate input.")
  if (!is.null(true)  && !true  %in% x) stop("Inappropriate value for `true`")
  if (!is.null(false) && !false %in% x) stop("Inappropriate value for `true`")
  x[x %in% na.values] <- NA

  if (is.null(true) | is.null(false)) {
    tf <- sort(setdiff(unique(x),false))
    if (is.null(true)) true <- tf[1]
    false <- setdiff(tf,true)
    message(true," is set to TRUE, ",false, " is set to FALSE")
  }
  x == true
}
moodymudskipper/hidden documentation built on May 20, 2019, 9:59 a.m.