R:如何使用 data.table 的函数输入创建一个函数

2023-12-28

我在使用 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R:如何使用 data.table 的函数输入创建一个函数 的相关文章

随机推荐