Jaken
Jaken

Reputation: 521

How to pass formulas to dplyr::case_match()

I frequently need to make long, customized changes to labels or variable names in a variety of settings. dplyr::case_match() is great for this, with a lot of customization options. For example:

library(dplyr)
x <- c("a", "b", "a", "d", "b", "c")

y <- case_match(x,
  "a" ~ 1,
  "b" ~ 2,
  "c" ~ 3,
  "d" ~ 4
)

However, the list of formulas can get very long and unwieldy, especially when they're longer strings. I'd love to be able to save them as a list (or something) and then pass them as an argument to case_match(). That way I could keep them in a separate section of customizable parameters, and not have to dig deep into the code any time I need to change a unit. What I'd like to do is something like this:

labelswitch <- 
       c("a" ~ 1,
       "b" ~ 2,
       "c" ~ 3,
       "d" ~ 4)

y <- case_match(x, labelswitch)

But this throws an error: Error in case_match(): ! Case 1 (z) must be a two-sided formula, not a list.

My current fix is to throw the whole thing into its own little function, which isn't a terrible solution, but does require a little more digging if I want to change up labels on the fly. Is there any way to just past the list of formulas directly?

#function solution - works but a little annoying
cmfun <- function(x) {
  case_match(x,
  "a" ~ 1,
  "b" ~ 2,
  "c" ~ 3,
  "d" ~ 4
  )
}

cmfun(x)

Upvotes: 0

Views: 40

Answers (0)

Related Questions