Note that in this question I want a column of functions, so it's not a duplicate of the more common question "how do I create a new column using a function?".
I'll demonstrate with a simple working example. The func
column is a list of functions.
test <- data.table(n = c(1, 1, 2, 2), func = c(min, min, max, max))
The syntax to actually use the function is a little unexpected to me but I can get it to work like this:
test[1, func][[1]](c(1,2)) # the unexpected part being that I have to include [[1]]
Now, let's create a larger data.table
, and add the goal that I want the func
column to be based on the n
column. Using data.table::fcase
results in an error:
test3 <- data.table(n = c(1, 1, 2, 2))
test3[, func := fcase(n == 1, min,
n == 2, max)]
# Error in fcase(n == 1, min, n == 2, max) :
# invalid type/length (builtin/4) in vector allocation
Why does this method fail? And how can I update the assignment of func
to be based on column n
? I'm curious if there is a data.table
solution to this.