R:将参数作为向量进行映射

R: mapply with parameters as vector

背景: 我想使用 mapply 函数在 data.table 中创建附加列。此列设计为由具有可变结构和可变参数数量的函数计算,因此我将mapply函数定义作为解析的字符串传递。

library(data.table)

dt = data.table(x1 = c(1,2,3,4), x2 = c(3,4,5,2), x3 = c(3,4,5,2))
body <- "(x1 + x2) * x3"
args <- "x1, x2, x3"
fla = eval(parse(text = paste('f <- function(', args, ') { return(' , body , ')}', sep='')))
res_dt = dt[, k := mapply(fla, x1, x2, x3)]

这部分代码 returns 以下预期结果:

res_dt

   x1 x2 x3  k
1:  1  3  3 12
2:  2  4  4 24
3:  3  5  5 40
4:  4  2  2 12

但是要转换的其他列的公式可以有其他数量的参数,因此我需要在我的函数中将参数作为向量传递。 但是当我按照下面的描述尝试这样做时:

p = c('x1','x2','x3')
res_dt = dt[, k_fin := mapply(fla, p)]

我收到以下错误:

> res_dt = dt[, k_fin := mapply(fla, p)]
Error in (function (x1, x2, x3)  : 
  argument "x2" is missing, with no default

我的问题是: 如何在我的函数中传递带参数的向量以使其工作?

非常感谢您。

也许这种方法会有所帮助:

简答:

p = c("fla", 'x1','x2','x3') #provide all arguments in a vector
res_dt = dt[, k_fin := do.call(mapply, as.list(get(p)))] #get objects named in p and convert them to a list, and provide that list as arguments to mapply

可重现:

library(data.table)

dt = data.table(x1 = c(1,2,3,4), x2 = c(3,4,5,2), x3 = c(3,4,5,2))
body <- "(x1 + x2) * x3"
args <- "x1, x2, x3"
fla = eval(parse(text = paste('f <- function(', args, ') { return(' , body , ')}', sep='')))
p = c("fla", 'x1','x2','x3')
res_dt = dt[, k_fin := do.call(mapply, as.list(get(p)))]
#output
   x1 x2 x3 k_fin
1:  1  3  3    12
2:  2  4  4    24
3:  3  5  5    40
4:  4  2  2    12