以下是一个示例代码,演示如何编写一个自定义的 case_when 函数,以在 dplyr 的 mutate 函数中使用 tidyeval:
library(dplyr)
library(rlang)
# 自定义的 case_when 函数
case_when2 <- function(...) {
  exprs <- enquos(...)
  result <- NULL
  
  for (i in seq_along(exprs)) {
    condition <- exprs[[i]]
    
    if (i == length(exprs)) {
      result <- expr(condition)
    } else {
      result <- expr(!!condition ~ !!result)
    }
  }
  
  return(result)
}
# 示例数据
df <- data.frame(a = 1:5, b = c("A", "B", "C", "D", "E"))
# 使用自定义的 case_when2 函数
df_new <- df %>%
  mutate(c = case_when2(
    a == 1 ~ "One",
    a == 2 ~ "Two",
    a == 3 ~ "Three",
    a == 4 ~ "Four",
    a == 5 ~ "Five",
    TRUE ~ "Other"
  ))
# 输出结果
df_new
在上述代码中,我们定义了一个名为 case_when2 的函数,该函数接受多个条件和结果,并使用 enquos 将这些条件和结果转换为语法树。然后,我们遍历条件列表,并使用 expr 和 !! 运算符将条件和结果组合在一起。最后,我们返回结果。在 mutate 函数中使用 case_when2 函数时,我们需要使用 !! 运算符对条件进行求值。
运行上述代码将输出一个新的数据框 df_new,其中包含根据条件转换后的新列 c。