使用dplyr mutate_at和自定义函数

ZRo*_*oss 6 r dplyr

我想从表中取两个变量并将它们除以第三个变量,并将这些计算添加为两个新列.该mutate_at()让我非常接近,但在自定义函数中,f()下面,我想在数据集中访问另一列.任何建议或替代整洁的工具方法?

library(dplyr)
# this works fine but is NOT what I want
f <- function(fld){
  fld/5
}

# This IS what I want where wt is a field in the data
f <- function(fld){
  fld/wt
}

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

# This works but is pretty clumsy
f <- function(fld, dat) fld/dat$wt
mutate_at(mtcars, .vars = vars(mpg, cyl), .funs = funs(xyz = f(., mtcars)))

# This is closer but still it would be better if the function allowed the dataset to be submitted to the function without restating the name of the dataset

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

mutate_at(mtcars, .vars = vars(mpg, cyl), .funs = funs(xyz = f(., wt)))
Run Code Online (Sandbox Code Playgroud)

Ice*_*can 9

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

mtcars %>% 
  mutate_at(vars(mpg, cyl), f, denom = quote(wt))
Run Code Online (Sandbox Code Playgroud)

尽管在此特定示例中,不需要自定义功能.

mtcars %>% 
  mutate_at(vars(mpg, cyl), `/`, quote(wt))
Run Code Online (Sandbox Code Playgroud)


csg*_*oen 7

也许是这样的?

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

mtcars %>%
    mutate_at(vars(mpg,cyl), .funs = funs(xyz = f(.,wt)))
Run Code Online (Sandbox Code Playgroud)