如何使 case_when 中的双边公式的数量取决于参数的数量?

How do I make the number of two-sided formulas in case_when depend on the number of arguments?

我想在下面概括两个函数。我希望通用函数被称为 likert_score.

a 是一个字符向量。 length(a)应该是公式TRUE ~ x之前的双边公式的个数。我怎样才能制作这个功能或代表?

likert_score_4 <- function(x, a){
  a_seq <- seq_along(a) %>% as.character
  
  case_when(
    x == a[1] ~ a_seq[1],
    x == a[2] ~ a_seq[2],
    x == a[3] ~ a_seq[3],
    x == a[4] ~ a_seq[4],
    TRUE ~ x
  )
}


likert_score_5 <- function(x, a){
  case_when(
    x == a[1] ~ a_seq[1],
    x == a[2] ~ a_seq[2],
    x == a[3] ~ a_seq[3],
    x == a[4] ~ a_seq[4],
    x == a[5] ~ a_seq[5],
    TRUE ~ x
  )
}
likert_score <- function(x, a){
   recode(x, !!!setNames(as.character(seq_along(a)), a))
}
  • match(x,a)x的每个值查找a中匹配元素的索引,如果没有匹配
  • NA
  • ifelse() 将 non-matching 值替换为 x 的相应值(也可以说 x[!is.na(m)] <- na.omit(m)
  • 然后我们使用 as.character() 以备不时之需
likert_score <- function(x,a ) {
  m <- match(x, a)
  as.character(ifelse(is.na(m), x, m))
}
a <- LETTERS[1:4]
set.seed(101)
x <- sample(LETTERS[1:5], size = 20, replace = TRUE)
identical(likert_score_4(x,a), likert_score(x,a))  ## TRUE

或者如果你想让它高深莫测 pipe-y:

match(x,a) %>% ifelse(test = is.na(.), yes = x) %>% as.character()