背景:
我想使用data.table
函数在mapply
中创建其他列。该列旨在通过具有可变结构和可变数量参数的函数来计算,因为我将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)]
这部分代码返回以下预期结果:
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
我的问题是: 如何在函数中传递带有参数的vector使其起作用?
非常感谢您。
答案 0 :(得分:1)
也许这种方法可能有用:
简短答案:
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