
Last chance! 50% off unlimited learning
Sale ends in
Provides pipe-friendly functions to convert simultaneously multiple variables into a factor variable.
Helper functions are also available to set the reference level and the levels order.
convert_as_factor(data, ..., vars = NULL, make.valid.levels = FALSE)set_ref_level(data, name, ref)
reorder_levels(data, name, order)
a data frame
one unquoted expressions (or variable name) specifying the name of
the variables you want to convert into factor. Alternative to the argument
vars
.
a character vector specifying the variables to convert into factor.
logical. Default is FALSE. If TRUE, converts the variable to factor and add a leading character (x) if starting with a digit.
a factor variable name. Can be unquoted. For example, use
group
or "group"
.
the reference level.
a character vector specifying the order of the factor levels
convert_as_factor
: Convert one or multiple variables into factor.
set_ref_level
: Change a factor reference level or group.
reorder_levels
: Change the order of a factor levels
# Create a demo data
df <- tibble(
group = c("a", "a", "b", "b", "c", "c"),
time = c("t1", "t2", "t1", "t2", "t1", "t2"),
value = c(5, 6, 1, 3, 4, 5)
)
df
# Convert group and time into factor variable
result <- df %>% convert_as_factor(group, time)
result
# Show group levels
levels(result$group)
# Set c as the reference level (the first one)
result <- result %>%
set_ref_level("group", ref = "c")
levels(result$group)
# Set the order of levels
result <- result %>%
reorder_levels("group", order = c("b", "c", "a"))
levels(result$group)
Run the code above in your browser using DataLab