Dplyr programming pattern for mutate

321 views Asked by At

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?

1

There are 1 answers

0
Paul On

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)