stabilize_fct {stbl} | R Documentation |
Ensure a factor argument meets expectations
Description
to_fct()
checks whether an argument can be coerced to
a factor without losing information, returning it silently if so.
Otherwise an informative error message is signaled.
stabilize_fct()
can check more details about the argument, but is slower
than to_fct()
.
stabilize_fct_scalar()
and to_fct_scalar()
are optimized to check for
length-1 factors.
Usage
stabilize_fct(
x,
...,
allow_null = TRUE,
allow_na = TRUE,
min_size = NULL,
max_size = NULL,
levels = NULL,
to_na = character(),
x_arg = caller_arg(x),
call = caller_env(),
x_class = object_type(x)
)
stabilize_fct_scalar(
x,
...,
allow_null = TRUE,
allow_zero_length = TRUE,
allow_na = TRUE,
levels = NULL,
to_na = character(),
x_arg = caller_arg(x),
call = caller_env(),
x_class = object_type(x)
)
to_fct(
x,
allow_null = TRUE,
levels = NULL,
to_na = character(),
x_arg = caller_arg(x),
call = caller_env(),
x_class = object_type(x)
)
to_fct_scalar(
x,
allow_null = TRUE,
allow_zero_length = TRUE,
levels = NULL,
to_na = character(),
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 |
max_size |
Integer. The maximum size of the object. Object size will be
tested using |
levels |
Character. Expected levels. If |
to_na |
Character. Values to coerce to |
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 |
x_class |
Character. The class name of |
allow_zero_length |
Logical. Are zero-length vectors acceptable? |
Details
These functions have important differences from base::as.factor()
and
base::factor()
:
Values are never silently coerced to
NA
unless they are explicitly supplied in theto_na
argument.-
NULL
values can be rejected as part of the call to this function (withallow_null = FALSE
).
Value
The argument as a factor.
Examples
to_fct("a")
to_fct(1:10)
to_fct(NULL)
try(to_fct(letters[1:5], levels = c("a", "c"), to_na = "b"))
to_fct_scalar("a")
try(to_fct_scalar(letters))
stabilize_fct(letters)
try(stabilize_fct(NULL, allow_null = FALSE))
try(stabilize_fct(c("a", NA), allow_na = FALSE))
try(stabilize_fct(c("a", "b", "c"), min_size = 5))
try(stabilize_fct(c("a", "b", "c"), max_size = 2))
stabilize_fct_scalar("a")
try(stabilize_fct_scalar(letters))
try(stabilize_fct_scalar("c", levels = c("a", "b")))