使用data.table进行锻炼时遇到了问题。这是我的问题。我写了一个简单的减法函数:
minus <- function(a, b){
return(a - b)
}
我的数据集是一个简单的data.table:
dt <- as.data.table(data.frame(first=c(5, 6, 7), second=c(1,2,3)))
dt
first second
1 5 1
2 6 2
3 7 3
我想写另一个功能,
myFunc <- function(dt, FUN, ...){
return(dt[, new := FUN(...)])
}
用法很简单:
res <- myFunc(dt, minus, first, second)
结果将是以下内容:
res
first second new
1: 5 1 4
2: 6 2 4
3: 7 3 4
如何归档这样的目标?谢谢!
最佳答案
也许有更好的方法,但是您可以尝试如下操作:
myFunc <- function(indt, FUN, ...) {
FUN <- deparse(substitute(FUN)) # Get FUN as a string
FUN <- match.fun(FUN) # Match it to an existing function
dots <- substitute(list(...))[-1] # Get the rest of the stuff
# I've used `copy(indt)` so that it doesn't affect your original dataset
copy(indt)[, new := Reduce(FUN, mget(sapply(dots, deparse)))][]
}
(请注意,这非常特定于您创建
minus()
函数的方式。)它在起作用:
res <- myFunc(dt, minus, first, second)
dt ## Unchanged
# first second
# 1: 5 1
# 2: 6 2
# 3: 7 3
res
# first second new
# 1: 5 1 4
# 2: 6 2 4
# 3: 7 3 4