Steph Locke
Steph Locke

Reputation: 6146

Pass an aliased column into a function for use in data.table `by=` argument

I would like to be able to do lots of bulk processing on a data.table grouped by different attributes.

I have a function which allows this to be done by passing it a string for the column intended to be grouped:

library(data.table)

myaggfunction<-function(mydt,aggcol,type){
  mydt[,lapply(.SD, sum), by=aggcol][,Type:=type]
}

myaggfunction(as.data.table(iris),"Species","Test")[]

However, some columns need to be aliased in the output. I know I can pass a string to by but how do you pass a list equivalent that does not get evaluated at the function parameter level e.g.

myaggfunction(as.data.table(iris),list(IrisSpecies=Species),"Test")[]

Upvotes: 4

Views: 409

Answers (1)

shadow
shadow

Reputation: 22323

You can use substitute to get the unevaluated expression and pass it on to the by in data.table.

library(data.table)

myaggfunction<-function(mydt,aggcol,type){
  aggcol <- substitute(aggcol)
  mydt[,lapply(.SD, sum), by=aggcol][,Type:=type]
}

myaggfunction(as.data.table(iris),"Species","Test")[]
myaggfunction(as.data.table(iris),list(IrisSpecies=Species),"Test")[]

Upvotes: 2

Related Questions