Why is the LHS the condition and the RHS the output for dplyr's case_when()?

Viewed 81

In a regression or plotting context, the formula/tilde syntax is used to mean something like "The value of the LHS is dependent on the RHS". For example

lattice::xyplot(mpg ~ disp, data=mtcars)

displays disp as the x/independent variable and mpg as the y/dependent variable. However with dplyr::case_when() this logic seems reversed. The LHS contains the condition, while the RHS contains what is returned if the condition is TRUE. Hence the RHS is dependent on the LHS. Why is this dependency relationship reveresed for case_when() compared to other uses of formula syntax in R? Which is perhaps a different way of asking, why is my interpretation of what case_when() is doing wrong?

1 Answers

This is my theory. case_when extends else_if, and aims to be a if-then-else (case-when-else) that SQL and other language have. Think of ~ as a shortcut for then.

Looking at the source code https://github.com/tidyverse/dplyr/blob/c2a3fca9ab85dd847605c7fda1d6b0b971f9381a/R/case-when.R case_when uses the function meaning of ~ as a method to split the arguments, see docs for ?rlang::f_lhs().

Finally, this format is about readability, I've written several long data clean-up scripts with multiline case_when's, and they are readable thanks to this layout.

Related