Created
August 13, 2017 20:37
-
-
Save marcmtk/5aa6bc3fea3008f1c8e13b76c56ec580 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```{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