Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add column names to data.table when aggregating

Tags:

r

data.table

I know we can dynamically add column names when creating columns by reference (using :=), as described e.g. here: Dynamic column names in data.table.

However, I'm looking to dynamically add column names when we aggregate. 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) =
like image 527
ArunK Avatar asked Nov 27 '25 21:11

ArunK


1 Answers

As mentioned in the comments by lukeA, setNames can be used:

m <- c("blah", "foo")
test_dtb[ , setNames(list(mean(b), median(b)), m), by = id] 
like image 170
ArunK Avatar answered Nov 30 '25 12:11

ArunK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!