在进行数据分析时,有时我需要将值重新编码为因子以进行组分析。我想保持因子的顺序与指定的转换顺序相同case_when
。在这种情况下,顺序应该是"Excellent" "Good" "Fail"
。我怎样才能做到这一点而不像在中那样繁琐地再次提及它levels=c('Excellent', 'Good', 'Fail')
?
非常感谢。
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