3

I have been using a standard pattern when using dplyr mutate inside functions. Here is a toy example(only to prove a point):

myFunction = function(colname) {
    dots <- setNames(list(lazyeval::interp(~ifelse(x>25, x*10, x/10), x = quote(colname))), "my_new_col")
    mutate_(mtcars, .dots = dots)
}

I have made this into a function to not type it out every time. But this is rather verbose and I am not sure if there is a simpler way to parameterize calls to mutate_. Suggestions?

Sid
  • 420
  • 1
  • 6
  • 11
  • 4
    What are you trying to do with this code? – acylam Sep 12 '17 at 20:23
  • This is just a toy example. I am trying to parameterize calls to dplyr's mutate and filter by putting them inside a function. – Sid Sep 12 '17 at 22:29
  • "made it into a function to not type it out every time". Type what out exactly? Perhaps you could provide an example where you _don't_ put it into a function. Your toy example doesn't have `filter` in it either – acylam Sep 12 '17 at 23:33

1 Answers1

2

I'm assuming your function is trying to create a new column based on an existing column. Here is the function using the tidyeval approach. See Programming with dplyr for details.

myFunction = function(df, col, new_col) {
    col <- enquo(col)
    new_col <- quo_name(enquo(new_col))

    df %>% 
        mutate(!!new_col := ifelse((!!col) > 25, (!!col) * 10, (!!col) / 10))
}

myFunction(mtcars, mpg, mpg_based_new_col)
Paul
  • 346
  • 3
  • 8