theArun theArun - 4 years ago 139
R Question

Dynamically add column names to data.table when aggregating

I know we can dynamically add column names as in this particular post dynamic column names in data.table, R.
However, I'm looking to dynamically add column names when we do aggregation using data.tables. Can you help with this?

test_dtb <- data.table(a=sample(1:100, 100),b=sample(1:100, 100),id=rep(1:10,10))
m = "blah"
test_dtb[,list((m) = mean(b)),by = id]

The error I get is

Error: unexpected '=' in "test_dtb[,list((m) =

Answer Source

as mentioned in the comments by lukeA:

m = c("blah", "foo");test_dtb[,setNames(list(mean(b),median(b)), m),by = id]? 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download