Search code examples
rcaselikert

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


I have two functions that I want to generalize below. I would like the generic function be called likert_score.

a is a vector of characters. length(a) should be the number of two-sided formulas before the formula TRUE ~ x. How can I make this function or a reprex?

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
  )
}

Solution

  • likert_score <- function(x, a){
       recode(x, !!!setNames(as.character(seq_along(a)), a))
    }