【问题标题】:R: How can I make a function with a function input with data.tableR:如何使用 data.table 输入函数来创建函数
【发布时间】:2015-11-25 08:13:52
【问题描述】:

我在使用 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

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

【问题讨论】:

    标签: r function input data.table


    【解决方案1】:

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

    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
    

    【讨论】:

    • 谢谢!如果我想根据输入更改新的列名怎么办?
    • @Nal-rA,也许用setnames?
    • 是的,这是可行的。再次感谢您!
    • 如果我的减号函数变成minus &lt;- function(a, b, c)怎么办?您的解决方案似乎不起作用。
    • 您可能需要do.call 而不是Reduce。现在不在我的电脑前...
    【解决方案2】:

    这是do.call的解决方案:

    myFunc <- function(dt, FUN, ...){
      arg.names <- as.character(match.call()[-(1:3)])
      copy(dt)[, "new" := do.call(FUN, lapply(arg.names, function(x) get(x)))]
    }
    #test
    myFunc(dt, minus, first, second)
    #   first second new
    #1:     5      1   4
    #2:     6      2   4
    #3:     7      3   4
    

    【讨论】:

      猜你喜欢
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 2015-10-12
      • 2021-09-09
      • 2019-11-05
      相关资源
      最近更新 更多