Using dplyr mutate_at with custom function

Updated version for dplyr 1.0.6:

mtcars %>% 
  mutate(across(c(mpg, cyl), ~ . / wt))

Or this, which may be slower

mtcars %>% 
  mutate(across(c(mpg, cyl), `/`, wt))

Previous answer:

library(tidyverse)
f <- function(num, denom) num/denom

mtcars %>% 
  mutate_at(vars(mpg, cyl), f, denom = quote(wt))

Although in this specific example, a custom function isn't needed.

mtcars %>% 
  mutate_at(vars(mpg, cyl), `/`, quote(wt))

Maybe something like this?

f <- function(fld,var){
    fld/var
}

mtcars %>%
    mutate_at(vars(mpg,cyl), .funs = funs(xyz = f(.,wt)))

Edit (2020-08-24):

As of second semester of 2020, with the launch of dplyr 1.0.0, mutate_at has been superseded by combining mutate with the across function:

mtcars %>%
    mutate(across(c(mpg, cyl), ~ f(.,wt), .names = "{col}_xyz"))

Tags:

R

Dplyr