Skip to content

Instantly share code, notes, and snippets.

@marcmtk
Last active August 13, 2017 20:34
Show Gist options
  • Save marcmtk/96dce028aff6768e1d47e3b6099369ba to your computer and use it in GitHub Desktop.
Save marcmtk/96dce028aff6768e1d47e3b6099369ba to your computer and use it in GitHub Desktop.
```{r}
library(tidyverse)
library(rlang)
meddle <- function(.data, ...) {
formulas <- quos(...)
xprs <- exprs(!!!formulas)
vars <- map_chr(xprs, all.vars) #Extract variables from formulas
build_cases <- function(var, formulas) { #Build case_when statements from the given formulas
var_sym <- as.symbol(var)
expr(case_when(!!!formulas, TRUE ~ !!var_sym))
}
rules <- map(unique(vars), ~ build_cases(.x, formulas[.x == vars])) #One statement pr var
names(rules) <- unique(vars) #Naming the statements to direct mutate
print(rules) #Just to show the workings for twitter
mutate(.data, !!!rules)
}
meddle(mtcars, gear == 4 ~ 8, vs == 1 ~ NA_real_, gear == 3 ~ 7) %>% tail(10)
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment