Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How can I make a function with a function input with 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)
  }

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

I would like to write another function,

myFunc <- function(dt, FUN, ...){
      return(dt[, new := FUN(...)])
  }

The usage is simply:

res <- myFunc(dt, minus, first, second)

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!

like image 397
morningfin Avatar asked Jul 27 '26 05:07

morningfin


1 Answers

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.)

Here it is in action:

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
like image 73
A5C1D2H2I1M1N2O1R2T1 Avatar answered Jul 30 '26 02:07

A5C1D2H2I1M1N2O1R2T1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!