newbie
newbie

Reputation: 907

How to create function for data.table

I want to create a function used for data.table. Supposed we have

library(data.table)    
DT = data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)

    foo <- function(data, field, grp){
      data[, field, by=grp]
    }

I have tried

   foo(DT, .N, grp = y)

or

   foo(DT, y)

They return errors. How do I pass input arguments in the data.table?

Upvotes: 0

Views: 136

Answers (1)

IRTFM
IRTFM

Reputation: 263479

You are in essence asking to reinvent the function [.data.table. The [ function perform an implicit evaluation of the second argument, j, in the context of the datatable. In the case of getting counts by groups it's just:

DT[ ,.N, by=y]
   y N
1: 1 3
2: 3 3
3: 6 3

Had you wanted sequences by groups it could have been:

> DT[ ,1:.N, by=y]
   y V1
1: 1  1
2: 1  2
3: 1  3
4: 3  1
5: 3  2
6: 3  3
7: 6  1
8: 6  2
9: 6  3

Upvotes: 1

Related Questions