Reputation: 440
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?
Upvotes: 3
Views: 303
Reputation: 346
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)
Upvotes: 2