我想从一个表中取出两个变量,将它们除以第三个变量,并将这些计算作为两个新列添加。 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)))
.funs=funs...
混乱,但那不是问题的重点。这只是另外两种方法,完全可以做到问题解决方案所做的事情:调用函数并在mutate()
内传递第二个参数。问题的关键是找到一种避免必须传递第二个参数的方法。 - randyf <- function(num) num/cur_data()$denom
,可以改进这个答案。如果您不介意,我会添加它。 - randy