factor_utils {tern}R Documentation

Factor utilities

Description

[Stable]

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

(factor)
factor variable or object to convert (for as_factor_keep_attributes).

levels

(character)
level names to be combined.

new_level

(string)
name of new level.

x_name

(string)
name of x.

na_level

(string)
which level to use for missing values.

verbose

(flag)
defaults to TRUE. It prints out warnings and messages.

discard

(character)
levels to discard.

condition

(logical)
positions at which to insert missing values.

.f

(factor or character)
original vector.

...

(named character)
levels in each vector provided will be collapsed into the new level given by the respective name.

.na_level

(string)
which level to use for other levels, which should be missing in the new factor. Note that this level must not be contained in the new levels specified in ....

Value

Functions

Note

Any existing NAs 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"))


[Package tern version 0.9.9 Index]