I occasionally need to rename all the levels of factor variable. I know how to achieve this with R base like: levels(factor_variable) <- levels(new_variable)
. But I would really like to have a way to do this kind of thing using tidyverse
. I look in dplyr
and forcats
but I do not found anything to solve it. I would like to be able to do what I achieve in example 1, but working with the %>%
operator.
Example 1, with R base (which works)
my_levels <- letters
sample_data <- data.frame(factor_data = factor(sample(my_levels,size = 500,replace = T) ,
levels = my_levels),
Any_other_data = rnorm(500))
my_new_levels <- rnorm(length(letters))
levels(sample_data$factor_data) <- levels(factor(my_new_levels))
Example 2, one thing I try and not work with tidyverse
library(tidyverse)
my_levels <- letters
sample_data <- tibble(factor_data = factor(sample(my_levels,size = 500,replace = T) ,
levels = my_levels),
Any_other_data = rnorm(500))
my_new_levels <- rnorm(length(letters))
# Get error
sample_data <- sample_data %>%
mutate(levels(factor_data) = levels(factor(my_new_levels)))
# Get error
sample_data <- sample_data %>%
mutate(factor_data = recode(factor_data, levels(factor_data) = levels(factor(my_new_levels))))
I also try with recode, but it is not only manually (each value at a time), but it also does not accept the %>%
operator. This is som things I try to see what happened:
sample_data <- sample_data %>%
recode(factor_data, a = '-2.5')
sample_data <- sample_data %>%
recode_factor(factor_data, a = '-2.5')
recode(sample_data$factor_data, levels(sample_data$factor_data) = levels(factor(my_new_levels)))
recode(sample_data$factor_data, a = '-2.5')
recode_factor(sample_data$factor_data, a = '-2.5')
levels(sample_data$factor_data) <- my_new_levels
. I don't see why you think a piped version would improve on this. – user2554330