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.- 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
groupor"group".- 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
#> # A tibble: 6 × 3
#> group time value
#> <chr> <chr> <dbl>
#> 1 a t1 5
#> 2 a t2 6
#> 3 b t1 1
#> 4 b t2 3
#> 5 c t1 4
#> 6 c t2 5
# Convert group and time into factor variable
result <- df %>% convert_as_factor(group, time)
result
#> # A tibble: 6 × 3
#> group time value
#> <fct> <fct> <dbl>
#> 1 a t1 5
#> 2 a t2 6
#> 3 b t1 1
#> 4 b t2 3
#> 5 c t1 4
#> 6 c t2 5
# Show group levels
levels(result$group)
#> [1] "a" "b" "c"
# Set c as the reference level (the first one)
result <- result %>%
set_ref_level("group", ref = "c")
levels(result$group)
#> [1] "c" "a" "b"
# Set the order of levels
result <- result %>%
reorder_levels("group", order = c("b", "c", "a"))
levels(result$group)
#> [1] "b" "c" "a"