Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to aggregate (using "by") a data.table with customized column name without ":="?

Tags:

r

data.table

I know I can do this

  a <- dt[,sum(x), by=y]

Also I can do this

  dt[,z:=sum(x), by=y] # this would modify dt

However I don't get why I cannot do this:

  a <- dt[,z=sum(x), by=y]

How should I perform a "summarize" with customized column names?

Is this the only option?

  a <- copy(dt)
  a[,z:=sum(x), by=y]
like image 580
colinfang Avatar asked Aug 15 '13 16:08

colinfang


1 Answers

You're looking for list() in the j argument:

a <- dt[,list(z=sum(x)), by=y]
like image 144
Señor O Avatar answered Sep 22 '22 16:09

Señor O