1

Using mutate_() I used to provide a list of new variables and the logic needed to create them.

library(dplyr)
library(rlang)

list_new_var <-
  list(new_1 = "am * mpg",
       new_2 = "cyl + disp")

mtcars %>% 
  mutate_(.dots = list_new_var) %>% 
  head()

Now I want to transition to using tidy evaluation. I am in the process of understanding the new methods.

How can I make this work? Will a function generally be recommended to solve this type of situation?

f_mutate <- function(data, new) {

  a <- expr(new)
  b <- eval(new)
  c <- syms(new)
  d <- UQ(syms(new))
  e <- UQS(syms(new))
  f <- UQE(syms(new))

  data %>%
    mutate(f) %>%
    head()

}

f_mutate(mtcars, new = list_new_var)
kputschko
  • 766
  • 1
  • 7
  • 21
  • For future reference, another way to accomplish this is using parse_quosure(). I could have done rlang_list <- list_new_var %>% lapply(rlang::parse_quosure); mtcars %>% mutate(!!! rlang_list) – kputschko Mar 20 '18 at 14:02

2 Answers2

4

One option would be to create a list with quote to return as an argument without evaluation

list_new_var <-list(
   new_1 = quote(am * mpg),
   new_2 = quote(cyl + disp)
)

and within the f_mutate, use the !!! to evaluate

f_mutate <- function(data, new) {

 data %>%
     mutate(!!! new) 
 }

run the function

f_mutate(mtcars, new = list_new_var) %>%
      head
#    mpg cyl disp  hp drat    wt  qsec vs am gear carb new_1 new_2
#1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4  21.0   166
#2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4  21.0   166
#3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1  22.8   112
#4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1   0.0   264
#5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2   0.0   368
#6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1   0.0   231
akrun
  • 874,273
  • 37
  • 540
  • 662
0

I don't think you need a function for this. I think you just need the following

library(dplyr)

  mtcars %>% 
  as_tibble() %>% 
  mutate(new_column1 = am * mpg,
         new_column2 = cyl + disp) %>% 
  head()

Check out the first example here.

Jenna Allen
  • 454
  • 3
  • 11
  • 1
    The thing is these new variables will be specified up front, in a user interface of sorts, so I'd like to pass in the variable creation logic, rather than actually creating the variable. – kputschko Feb 08 '18 at 03:22