R:如何使用data.table的函数输入创建函数 [英] R: How can I make a function with a function input with data.table

查看:198
本文介绍了R:如何使用data.table的函数输入创建函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用data.table执行时遇到问题。这是我的问题。我写了一个简单的减法函数:

I faced a problem when exercising with data.table. Here is my problem. I wrote a simple subtraction function:

minus <- function(a, b){
      return(a - b)
  }

我的数据集是一个简单的data.table:

My dataset is a simple 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)

,结果如下: p>

and the result would be the following:

res
   first second new
1:     5      1   4
2:     6      2   4
3:     7      3   4

如何归档这样的目标?谢谢!

How can I archive such a goal? Thanks!

推荐答案

也许有更好的方法,但你可以尝试这样:

Maybe there's a better way, but you can try something like this:

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)))][]
}

(注意这是非常明确的,

(Note that this is very specific to how you've created your minus() function.)

这里是操作中:

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

这篇关于R:如何使用data.table的函数输入创建函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆