在自定义函数中使用dplyr mutate_at
我想从一个表中取两个变量,然后将它们除以第三个变量,然后将这些计算作为两个新列添加。在自定义函数中使用dplyr mutate_at,r,dplyr,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 <
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)))
库(dplyr)
#这很好,但不是我想要的
也许是这样的
f <- function(fld,var){
fld/var
}
mtcars %>%
mutate_at(vars(mpg,cyl), .funs = funs(xyz = f(.,wt)))
为什么不简单
mutate(mtcars, mpg2 = mpg / wt, cyl2 = cyl / wt)
这适用于几个字段,但不灵活,如果有10个字段,会很麻烦。如果你改变了对后缀(“2”)的想法,你必须在几个地方改变它。同意,我想我错过了你问题的关键
mutate(mtcars, mpg2 = mpg / wt, cyl2 = cyl / wt)
library(tidyverse)
f <- function(num, denom) num/denom
mtcars %>%
mutate_at(vars(mpg, cyl), f, denom = quote(wt))
mtcars %>%
mutate_at(vars(mpg, cyl), `/`, quote(wt))