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!
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With