This function transforms a vector into a factor, assigns specified levels
and labels, and optionally handles missing values by explicitly assigning
them a level.
Usage
make_factor(input_vector, levels, labels, explicit_na = TRUE)
Arguments
- input_vector
A vector to be converted into a factor.
- levels
A vector of levels to be assigned to the factor.
- labels
A vector of labels corresponding to the levels.
- explicit_na
Logical, indicating whether missing values (NA) should
be explicitly assigned to a "Missing" level. Default is TRUE.
Value
A factor with specified levels and labels, potentially including
an explicit "Missing" level for NA values.
Details
This function allows for the creation of factors from a vector while
specifying both levels and labels.
If explicit_na
is set to TRUE
, missing values are explicitly
assigned to a level named "Missing".
The function also drops any unused levels from the factor.
Examples
vec <- c("low", "medium", "high", NA, "low")
levels <- c("low", "medium", "high")
labels <- c("Low", "Medium", "High")
make_factor(vec, levels, labels)