convert_as_factor {rstatix} | R Documentation |
Factors
Description
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.
Usage
convert_as_factor(data, ..., vars = NULL, make.valid.levels = FALSE)
set_ref_level(data, name, ref)
reorder_levels(data, name, order)
Arguments
data |
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. |
make.valid.levels |
logical. Default is FALSE. If TRUE, converts the variable to factor and add a leading character (x) if starting with a digit. |
name |
a factor variable name. Can be unquoted. For example, use
|
ref |
the reference level. |
order |
a character vector specifying the order of the factor levels |
Functions
-
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
Examples
# 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)