Skip to contents

Modified version of base::min() that differs in the following ways:

  • NAs in the input (...) are ignored by default (rm_na = TRUE).

  • If the input is of length zero, the output will also be of length zero (of the same type as the input).

  • It is ensured that all inputs are either numeric, of length zero or NA. The only case where the return value will be -Inf or NA is when the input contains only -Inf or NA.

  • Dynamic dots are supported.

Usage

safe_min(..., rm_na = TRUE)

Arguments

...

Numeric objects of which to determine the minimum. Dynamic dots are supported.

rm_na

Ignore missing values in .... If missing values are present and rm_na = FALSE, the result will always be NA.

Value

A numeric scalar or empty value, of the same type as ....

See also

Other statistical computing / numeric functions: round_to(), safe_max(), safe_seq_len(), stat_mode()

Examples

# other than `base::min()`, this function removes `NA`s by default
min(1, NA_real_, 2)
#> [1] NA
pal::safe_min(1, NA_real_, 2)
#> [1] 1

# other than `base::min()`, this function does not return `-Inf` or `NA_character_` for
# zero-length inputs
min(NULL)
#> Warning: no non-missing arguments to min; returning Inf
#> [1] Inf
min(integer())
#> Warning: no non-missing arguments to min; returning Inf
#> [1] Inf
pal::safe_min(NULL)
#> NULL
pal::safe_min(integer())
#> integer(0)

# other than `base::min()`, this function fails for non-numeric inputs
min("zero", 1L)
#> [1] "1"
min("zero", "one")
#> [1] "one"
min(character())
#> Warning: no non-missing arguments, returning NA
#> [1] NA
try(pal::safe_min("zero", 1L))
#> Error in purrr::map(input, function(x) checkmate::assert_numeric(x, typed.missing = TRUE,  : 
#>    In index: 1.
#> Caused by error in `.f()`:
#> ! Assertion on '...' failed: Must be of type 'numeric' (or 'NULL'), not 'character'.
try(pal::safe_min("zero", "one"))
#> Error in purrr::map(input, function(x) checkmate::assert_numeric(x, typed.missing = TRUE,  : 
#>    In index: 1.
#> Caused by error in `.f()`:
#> ! Assertion on '...' failed: Must be of type 'numeric' (or 'NULL'), not 'character'.
try(pal::safe_min(character()))
#> Error in purrr::map(input, function(x) checkmate::assert_numeric(x, typed.missing = TRUE,  : 
#>    In index: 1.
#> Caused by error in `.f()`:
#> ! Assertion on '...' failed: Must be of type 'numeric' (or 'NULL'), not 'character'.