Aggregate data table with column names as rows

I want to combine a column of the data table R, but specifying the column names as strings. Is it possible to do this using the capabilities of data tables?

For example, I want to reproduce:

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

but using strings for column names, for example:

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

I tried:

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

which works, but it is slow since it does not fully use the data table.

Thank!

+4
source share
2 answers

Usage get:

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

But I'm not sure that you will have the same performance as without use get.

+4
source

get , , , :

foo[, "newcol" := lapply(.SD, mean), by = "id", .SDcols = "oldcol"]
+3

Source: https://habr.com/ru/post/1544568/


All Articles