I would like to use dplyr case_when programmatically to replace the base function R cut() .
Currently, case_when can be used with an external argument via NSE, for example:
library(dplyr) library(rlang) patterns <- list( x <= 2 ~ "<=2", x <= 4 ~ "2<->4", x > 4 ~ ">4" ) x <- 1:10 case_when(!!!patterns)
What I want to do: use it with another variable inside the mutant
The idea would be like this, although I can't figure out how to make it work:
library(dplyr) patterns_lazy <- list( !!quo(x) <= 2 ~ "<=2", !!quo(x) <= 4 ~ "2<->4", !!quo(x) > 4 ~ ">4" ) x <- "cyl" mtcars %>% mutate(ABC = case_when(!!!patterns_lazy))
I would like to be able to define the column (inside the row) that I want to filter and retrieve something like this (this example does not work as the desired syntax):
x <- "cyl" mtcars %>% select(cyl) %>% mutate(ABC = case_when(!!!patterns_lazy)) %>% head() cyl ABC 1 6 >4 2 6 >4 3 4 2<->4 4 6 >4 5 8 >4 6 6 >4
Thanks for any help :)
source share