Ensure an argument meets expectations
Source:R/stabilize_arg.R
, R/stabilize_arg_scalar.R
stabilize_arg.Rd
stabilize_arg()
is used by other functions such as stabilize_int()
. Use
stabilize_arg()
if the type-specific functions will not work for your use
case, but you would still like to check things like size or whether the
argument is NULL.
stabilize_arg_scalar()
is optimized to check for length-1 vectors.
Usage
stabilize_arg(
x,
...,
allow_null = TRUE,
allow_na = TRUE,
min_size = NULL,
max_size = NULL,
x_arg = caller_arg(x),
call = caller_env(),
x_class = object_type(x)
)
stabilize_arg_scalar(
x,
...,
allow_null = TRUE,
allow_zero_length = TRUE,
allow_na = TRUE,
x_arg = caller_arg(x),
call = caller_env(),
x_class = object_type(x)
)
Arguments
- x
The argument to stabilize.
- ...
These dots are for future extensions and should be empty.
- allow_null
Logical. Is NULL an acceptable value?
- allow_na
Logical. Are NA values ok?
- min_size
Integer. The minimum size of the object. Object size will be tested using
vctrs::vec_size()
.- max_size
Integer. The maximum size of the object. Object size will be tested using
vctrs::vec_size()
.- x_arg
Character. An argument name for x. The automatic value will work in most cases, or pass it through from higher-level functions to make error messages clearer in unexported functions.
- call
The execution environment of the call. See the
call
argument ofrlang::abort()
for more information.- x_class
Character. The class name of
x
to use in error messages. Use this if you remove a special class fromx
before checking its coercion, but want the error message to match the original class.- allow_zero_length
Logical. Are zero-length vectors acceptable?
Examples
wrapper <- function(this_arg, ...) {
stabilize_arg(this_arg, ...)
}
wrapper(1)
#> [1] 1
wrapper(NULL)
#> NULL
wrapper(NA)
#> [1] NA
try(wrapper(NULL, allow_null = FALSE))
#> Error in wrapper(NULL, allow_null = FALSE) :
#> `this_arg` must not be <NULL>.
try(wrapper(NA, allow_na = FALSE))
#> Error in wrapper(NA, allow_na = FALSE) :
#> `this_arg` must not contain NA values.
#> • NA locations: 1
try(wrapper(1, min_size = 2))
#> Error in wrapper(1, min_size = 2) :
#> `this_arg` must have size >= 2.
#> ✖ 1 is too small.
try(wrapper(1:10, max_size = 5))
#> Error in wrapper(1:10, max_size = 5) :
#> `this_arg` must have size <= 5.
#> ✖ 10 is too big.
stabilize_arg_scalar("a")
#> [1] "a"
stabilize_arg_scalar(1L)
#> [1] 1
try(stabilize_arg_scalar(1:10))
#> Error in eval(expr, envir, enclos) :
#> `1:10` must be a single <integer>.
#> ✖ `1:10` has 10 values.