factor_utils {tern} | R Documentation |
Factor utilities
Description
A collection of utility functions for factors.
Usage
combine_levels(x, levels, new_level = paste(levels, collapse = "/"))
as_factor_keep_attributes(
x,
x_name = deparse(substitute(x)),
na_level = "<Missing>",
verbose = TRUE
)
fct_discard(x, discard)
fct_explicit_na_if(x, condition, na_level = "<Missing>")
fct_collapse_only(.f, ..., .na_level = "<Missing>")
Arguments
x |
( |
levels |
( |
new_level |
( |
x_name |
( |
na_level |
( |
verbose |
( |
discard |
( |
condition |
( |
.f |
( |
... |
(named |
.na_level |
( |
Value
-
combine_levels
: Afactor
with the new levels.
-
as_factor_keep_attributes
: Afactor
with same attributes (except class) asx
. Does not modifyx
if already afactor
.
-
fct_discard
: A modifiedfactor
with observations as well as levels fromdiscard
dropped.
-
fct_explicit_na_if
: A modifiedfactor
with inserted and existingNA
converted tona_level
.
-
fct_collapse_only
: A modifiedfactor
with collapsed levels. Values and levels which are not included in the givencharacter
vector input will be set to the missing level.na_level
.
Functions
-
combine_levels()
: Combine specified old factor Levels in a single new level. -
as_factor_keep_attributes()
: Convertsx
to a factor and keeps its attributes. Warns appropriately such that the user can decide whether they prefer converting to factor manually (e.g. for full control of factor levels). -
fct_discard()
: This discards the observations as well as the levels specified from a factor. -
fct_explicit_na_if()
: This inserts explicit missing values in a factor based on a condition. Additionally, existingNA
values will be explicitly converted to givenna_level
. -
fct_collapse_only()
: This collapses levels and only keeps those new group levels, in the order provided. The returned factor has levels in the order given, with the possible missing level last (this will only be included if there are missing values).
Note
Any existing NA
s in the input vector will not be replaced by the missing level. If needed,
explicit_na()
can be called separately on the result.
See Also
cut_quantile_bins()
for splitting numeric vectors into quantile bins.
forcats::fct_na_value_to_level()
which is used internally.
forcats::fct_collapse()
, forcats::fct_relevel()
which are used internally.
Examples
x <- factor(letters[1:5], levels = letters[5:1])
combine_levels(x, levels = c("a", "b"))
combine_levels(x, c("e", "b"))
a_chr_with_labels <- c("a", "b", NA)
attr(a_chr_with_labels, "label") <- "A character vector with labels"
as_factor_keep_attributes(a_chr_with_labels)
fct_discard(factor(c("a", "b", "c")), "c")
fct_explicit_na_if(factor(c("a", "b", NA)), c(TRUE, FALSE, FALSE))
fct_collapse_only(factor(c("a", "b", "c", "d")), TRT = "b", CTRL = c("c", "d"))