【发布时间】:2018-09-20 09:23:04
【问题描述】:
我想从表中取出两个变量,然后将它们除以第三个变量,然后将这些计算添加为两个新列。 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)))
【问题讨论】: