在进行数据分析时,为了进行分组分析,有时需要将数值重新编码为因子,我希望因子的顺序与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
5条答案
按热度按时间rkue9o1l1#
我的方案
最后,我想出了一个解决方案,对于感兴趣的人,这里是我的解决方案,我写了一个函数
fct_case_when
(假装是forcats
中的函数),它只是case_when
的一个带因子输出的 Package 器,层次的顺序和参数的顺序一样。现在,我可以使用
fct_case_when
代替case_when
,结果将与前面的实现相同(但不那么乏味)。3zwtqj6y2#
默认情况下,级别是按字典顺序设置的。如果不想指定级别,可以对其进行设置,使字典顺序正确(
Performance1
),或创建一次levels
向量,并在生成因子和设置水平时使用该向量(Performance2
)。我不知道这两种方法能为您节省多少精力或繁琐,但它们都在这里。看看我的第三条建议,我认为这是最不繁琐的方法。如果我能建议一个更简单的方法:
cngwdvgl3#
虽然我的解决方案用一个混乱的中间变量替换了管道,但它是有效的:
编辑修复!
idfiyjo84#
这是我一直在使用的一个实现:
这样做的优点是不必手动指定因子水平。
我还向dplyr提交了一个功能请求:https://github.com/tidyverse/dplyr/issues/6029
vyu0f0g15#
让
case_when()
输出数字,并在factor()
中使用labels
参数:创建于2023年1月13日,使用reprex v2.0.2