R:转换为水平顺序与case_when相同的因子

8e2ybdfx  于 2023-01-15  发布在  其他
关注(0)|答案(5)|浏览(95)

在进行数据分析时,为了进行分组分析,有时需要将数值重新编码为因子,我希望因子的顺序与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
rkue9o1l

rkue9o1l1#

我的方案

最后,我想出了一个解决方案,对于感兴趣的人,这里是我的解决方案,我写了一个函数fct_case_when(假装是forcats中的函数),它只是case_when的一个带因子输出的 Package 器,层次的顺序和参数的顺序一样。

fct_case_when <- function(...) {
  args <- as.list(match.call())
  levels <- sapply(args[-1], function(f) f[[3]])  # extract RHS of formula
  levels <- levels[!is.na(levels)]
  factor(dplyr::case_when(...), levels=levels)
}

现在,我可以使用fct_case_when代替case_when,结果将与前面的实现相同(但不那么乏味)。

Performance <- function(x) {                       
  fct_case_when(                                         
    is.na(x) ~ NA_character_,                          
    x > 80   ~ 'Excellent',                            
    x > 50   ~ 'Good',                                 
    TRUE     ~ 'Fail'                                  
  )
}      
performance <- Performance(score)                  
levels(performance)                       
#> [1] "Excellent" "Good"      "Fail"
table(performance)                
#> performance
#> Excellent      Good      Fail 
#>        15        30        55
3zwtqj6y

3zwtqj6y2#

默认情况下,级别是按字典顺序设置的。如果不想指定级别,可以对其进行设置,使字典顺序正确(Performance1),或创建一次levels向量,并在生成因子和设置水平时使用该向量(Performance2)。我不知道这两种方法能为您节省多少精力或繁琐,但它们都在这里。看看我的第三条建议,我认为这是最不繁琐的方法。

Performance1 <- function(x) {                       
  case_when(
    is.na(x) ~ NA_character_,                          
    x > 80 ~ 'Excellent',  
    x <= 50 ~ 'Fail',
    TRUE ~ 'Good',
  ) %>% factor()
}

Performance2 <- function(x, levels = c("Excellent", "Good", "Fail")){
  case_when(
    is.na(x) ~ NA_character_,
    x > 80 ~ levels[1],
    x > 50 ~ levels[2],
    TRUE ~ levels[3]
  ) %>% factor(levels)
}
performance1 <- Performance1(score)
levels(performance1)
# [1] "Excellent" "Fail"     "Good"
table(performance1)
# performance1
# Excellent      Fail      Good 
#        15        55        30 

performance2 <- Performance2(score)
levels(performance2)
# [1] "Excellent" "Good"      "Fail"  
table(performance2)
# performance2
# Excellent      Good      Fail 
#        15        30        55

如果我能建议一个更简单的方法:

performance <- cut(score, breaks = c(0, 50, 80, 100), 
                   labels = c("Fail", "Good", "Excellent"))
levels(performance)
# [1] "Fail"      "Good"      "Excellent"
table(performance)
# performance
#      Fail      Good Excellent 
#        55        30        15
cngwdvgl

cngwdvgl3#

虽然我的解决方案用一个混乱的中间变量替换了管道,但它是有效的:

library(dplyr, warn.conflicts = FALSE)             

set.seed(1234)                                     
score <- runif(100, min = 0, max = 100)     

Performance <- function(x) {                       
  t <- case_when(                                         
    is.na(x) ~ NA_character_,                          
    x > 80   ~ 'Excellent',                            
    x > 50   ~ 'Good',                                 
    TRUE     ~ 'Fail'                                  
  ) 
  to <- subset(t, !duplicated(t))
  factor(t, levels=(to[order(subset(x, !duplicated(t)), decreasing=T)] ))
}                                                  
performance <- Performance(score)                
levels(performance)

编辑修复!

idfiyjo8

idfiyjo84#

这是我一直在使用的一个实现:

library(dplyr)
library(purrr)
library(rlang)
library(forcats)

factored_case_when <- function(...) {
  args <- list2(...)
  rhs <- map(args, f_rhs)
  
  cases <- case_when(
    !!!args
  )
  
  exec(fct_relevel, cases, !!!rhs)
}

numbers <- c(2, 7, 4, 3, 8, 9, 3, 5, 2, 7, 5, 4, 1, 9, 8)

factored_case_when(
  numbers <= 2 ~ "Very small",
  numbers <= 3 ~ "Small",
  numbers <= 6 ~ "Medium",
  numbers <= 8 ~ "Large",
  TRUE    ~ "Huge!"
)
#>  [1] Very small Large      Medium     Small      Large      Huge!     
#>  [7] Small      Medium     Very small Large      Medium     Medium    
#> [13] Very small Huge!      Large     
#> Levels: Very small Small Medium Large Huge!

这样做的优点是不必手动指定因子水平。
我还向dplyr提交了一个功能请求:https://github.com/tidyverse/dplyr/issues/6029

vyu0f0g1

vyu0f0g15#

case_when()输出数字,并在factor()中使用labels参数:

library(dplyr, warn.conflicts = FALSE)
set.seed(1234)
score <- runif(100, min = 0, max = 100)

Performance <- function(x) {
  case_when(
    is.na(x) ~ NA_real_,
    x > 80   ~ 1,
    x > 50   ~ 2,
    TRUE     ~ 3
  ) %>% factor(labels=c('Excellent', 'Good', 'Fail'))
}

performance <- Performance(score)
levels(performance)
#> [1] "Excellent" "Good"      "Fail"
table(performance)
#> performance
#> Excellent      Good      Fail 
#>        15        30        55

创建于2023年1月13日,使用reprex v2.0.2

相关问题