Reputation: 1711
Just as the title, the code in mutate function equation
will be used many of my other code. I want to extract equation
so that if the code was wrong, I could quickly fix it.
How to let the mutate function recognizes theequation
vector.
library(tidyverse)
# can run
mtcars_2 <- mtcars %>% mutate(new_var_1 = case_when(mpg >= 20 ~ 1, TRUE ~ 0),
new_var_2 = case_when(cyl >= 4 ~ 1, TRUE ~ 0),
new_var_3 = case_when(hp >= 90 ~ 1, TRUE ~ 0))
# not run
equation <- "new_var_1 = case_when(mpg >= 20 ~ 1, TRUE ~ 0),
new_var_2 = case_when(cyl >= 4 ~ 1, TRUE ~ 0),
new_var_3 = case_when(hp >= 90 ~ 1, TRUE ~ 0)"
mtcars_2 <- mtcars %>% mutate(get(equation))
Any help will be highly appreciated.
Upvotes: 1
Views: 943
Reputation: 887038
We can use parse_exprs
library(rlang)
library(dplyr)
library(stringr)
equation <- "new_var_1 = case_when(mpg >= 20 ~ 1, TRUE ~ 0);
new_var_2 = case_when(cyl >= 4 ~ 1, TRUE ~ 0);
new_var_3 = case_when(hp >= 90 ~ 1, TRUE ~ 0)"
mtcars %>%
mutate(!!! parse_exprs(equation)) %>%
rename_at(vars(starts_with('new_var')), ~ str_remove(., "\\s+=.*")) %>%
head
# mpg cyl disp hp drat wt qsec vs am gear carb new_var_1 new_var_2 new_var_3
#Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 1 1 1
#Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 1 1 1
#Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 1 1 1
#Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 1 1 1
#Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 0 1 1
#Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 0 1 1
Upvotes: 1
Reputation: 206197
Rather than extracting this as an expression, just make it it's own function
myfun <- . %>% mutate(new_var_1 = case_when(mpg >= 20 ~ 1, TRUE ~ 0),
new_var_2 = case_when(cyl >= 4 ~ 1, TRUE ~ 0),
new_var_3 = case_when(hp >= 90 ~ 1, TRUE ~ 0))
mtcars %>% myfun()
Then you can add that as a step to any chain you like.
If you wanted to be able to add other variables in the same statement, you could do something more like
mymutate <- function(data, ...)
mutate(data, new_var_1 = case_when(mpg >= 20 ~ 1, TRUE ~ 0),
new_var_2 = case_when(cyl >= 4 ~ 1, TRUE ~ 0),
new_var_3 = case_when(hp >= 90 ~ 1, TRUE ~ 0), ...)
mtcars %>% mymutate(new_var_4 = new_var_1 & new_var_3)
Upvotes: 4