Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate data table with column names as strings

Tags:

r

data.table

I want to aggregate a column of a R data table but providing the column names as strings. Is it possible to do it using data table capabilities?

For example, I want to reproduce:

foo[,newcol:=mean(oldcol), by=id]

but using strings for column names, something like:

foo[,"newcol":=mean("oldcol"), by="id"]

I have tried:

foo[,"newcol":=mean(foo[["oldcol"]]), by="id"]

that works, but it is slow as it does not take full advantage of the data table.

Thank you!

like image 787
kahlo Avatar asked Feb 12 '23 17:02

kahlo


1 Answers

Using get:

 foo[,"newcol":=mean(get("oldcol")), by="id"]

But I am not sure that you will have the same performance as without using get.

like image 97
agstudy Avatar answered Feb 15 '23 10:02

agstudy