A simple reproducible example to pass arguments to data.table in a self-defined function in R

I have been googling this answer for a few hours. A lot of people have asked similar questions, but I did not find either a simple enough question or a straightforward answer. Here is my approach:

Assume that I want to do a simple group by in data.table:

mtcars = data.table(mtcars)
mtcars[,sum(mpg), gear]

# Here are the results
#   gear    V1
#1:    4 294.4
#2:    3 241.6
#3:    5 106.9

However, if I use a self-defined function to do this:

zz = function(data, var, group){
  return(data[,sum(var), group])
zz(mtcars, mpg, gear)

I got an error message:

Error in eval(bysub, parent.frame(), parent.frame()) :
object ‘gear’ not found

I’ve tried substitute, eval, quote, and other solutions, but none of them works. I wonder if anyone could give a more straightforward solution and explanation to this.

Thank you and happy Halloween!

Leave a Reply

Your email address will not be published. Required fields are marked *