When doing data analysis, I sometimes need to recode values to factors in order to carry out groups analysis. I want to keep the order of factor same as the order of conversion specified in case_when. In this case, the order should be "Excellent" "Good" "Fail". How can I achieve this without tediously mention it again as in levels=c('Excellent', 'Good', 'Fail')?
Thank you very much.
library(dplyr, warn.conflicts = FALSE)
set.seed(1234)
score <- runif(100, min = 0, max = 100)
Performance <- function(x) {
case_when(
is.na(x) ~ NA_character_,
x > 80 ~ 'Excellent',
x > 50 ~ 'Good',
TRUE ~ 'Fail'
) %>% factor(levels=c('Excellent', 'Good', 'Fail'))
}
performance <- Performance(score)
levels(performance)
#> [1] "Excellent" "Good" "Fail"
table(performance)
#> performance
#> Excellent Good Fail
#> 15 30 55
levels = sapply(levels, FUN = eval)on the second-to-last line. This makes it possible to doresult = fct_case_when(x < 5 ~ my_vec[3])and not getting "my_vec[3]" asresult. - Jonas Lindeløv