Skip to contents

Check if arg is a vector of probabilities (numeric vector bounded by [0, 1]).

Usage

check_probability(arg, signal = "error", msg = NULL, call. = FALSE)

Arguments

arg

(object)
The argument to check.

signal

(string: c("error", "warning", "message"))
Must be one of "error", "warning", or "message". "error" (default) calls base::stop() to signal an error message. "warning" calls base::warning() to signal a warning message. "message" calls base::message() to signal a message.

msg

(string or NULL: NULL)
A string that replaces the default message. Set as NULL to use the default message.

call.

(Scalar logical: c(FALSE, TRUE))
Passed to stop() or warning(). The default msg includes it's own formatted call, hence call. should be FALSE (default). If you insert your own msg, then you may want call. = TRUE.

Value

invisible(arg) or condition determined by argument signal.

Examples

#----------------------------------------------------------------------------
# check_probability() examples
#----------------------------------------------------------------------------
library(bkcheck)

f <- function(x) {
  x |>
    check_probability()
}

logical <- TRUE
integer <- 1L
numeric <- c(0.5, 1)
numeric2 <- c(0.5, 1.5)
character <- letters[1:4]
factor <- factor(character)

f(integer)
f(numeric)

try(f(logical))
#> Error : Argument `x` must be a vector of probabilities in [0, 1].
#> 
#> min(x, na.rm = TRUE) = 1
#> max(x, na.rm = TRUE) = 1
#> class(x) = 'logical'
#> length(x) = 1
#> 
#> Call: f(x = logical)
try(f(numeric2))
#> Error : Argument `x` must be a vector of probabilities in [0, 1].
#> 
#> min(x, na.rm = TRUE) = 0.5
#> max(x, na.rm = TRUE) = 1.5
#> class(x) = 'numeric'
#> length(x) = 2
#> 
#> Call: f(x = numeric2)
try(f(character))
#> Error : Argument `x` must be a vector of probabilities in [0, 1].
#> 
#> min(x, na.rm = TRUE) = a
#> max(x, na.rm = TRUE) = d
#> class(x) = 'character'
#> length(x) = 4
#> 
#> Call: f(x = character)
try(f(factor))
#> Error : Argument `x` must be a vector of probabilities in [0, 1].
#> 
#> min(x, na.rm = TRUE) = NA
#> max(x, na.rm = TRUE) = NA
#> class(x) = 'factor'
#> length(x) = 4
#> 
#> Call: f(x = factor)