I'm looking for a way to optimize an aggregate in data.table, I have several million data and my current implementation is slow.
Reproducible example:
library(data.table)
df <- data.table(Factor = as.factor(rep(LETTERS[1:3], 3)),
Variable = 1:9)
Current implementation:
aux <- df[, .(sumVar = sum(Variable)/sum(df$Variable)), by = .(Factor)]
df[aux, sumVar := sumVar, on = .(Factor = Factor)]
Desired output:
> df
Factor Variable sumVar
1: A 1 0.2666667
2: B 2 0.3333333
3: C 3 0.4000000
4: A 4 0.2666667
5: B 5 0.3333333
6: C 6 0.4000000
7: A 7 0.2666667
8: B 8 0.3333333
9: C 9 0.4000000
I think my problem is in the merge, but I do not know how to improve it, I am not familiar with dplyr and I have not found any way to do the operation in one step with data.table.
Any help is appreciated!