Dplyr function to replace nested ifelse (like SQL CASE WHEN)

I hate nested ifelse statements in R code. I absolutely hate them. They are just ugly and difficult to read. I found this lovely function in dplyr called case_when (which is like the SQL CASE WHEN if you know that) that banished them forever. It’s easier if I just show you (this is from the documentation)

x <- 1:50
  x %% 35 == 0 ~ "fizz buzz",
  x %% 5 == 0 ~ "fizz",
  x %% 7 == 0 ~ "buzz",
  TRUE ~ as.character(x)

How wonderful is that? No more nested ifelse!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.