简体   繁体   中英

How to use a vector in mutate function with dplyr in r

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 the equation 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.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM