I've got a very large dataset (millions of rows that I need to loop through thousands of times), and during the loop I have to do a conditional sum that appears to be taking a very long time. Is there a way of making this more efficient?
Datatable format as follows:
DT <- data.table('A' = c(1,1,1,2,2,3,3,3,3,4),
'B' = c(500,510,540,500,540,500,510,519,540,500),
'C' = c(10,20,10,20,10,50,20,50,20,10))
| A | B | C |
|---|---|---|
| 1 | 500 | 10 |
| 1 | 510 | 20 |
| 1 | 540 | 10 |
| 2 | 500 | 20 |
| 2 | 540 | 10 |
| 3 | 500 | 50 |
| 3 | 510 | 20 |
| 3 | 519 | 50 |
| 3 | 540 | 20 |
| 4 | 500 | 10 |
I need the sum of column C (in a new column, D) subject to A == A, and B >= B & B < B + 20 (by row). So the output table would look like the following:
| A | B | C | D |
|---|---|---|---|
| 1 | 500 | 10 | 30 |
| 1 | 510 | 20 | 30 |
| 1 | 540 | 10 | 10 |
| 2 | 500 | 20 | 20 |
| 2 | 540 | 10 | 10 |
| 3 | 500 | 50 | 120 |
| 3 | 510 | 20 | 120 |
| 3 | 519 | 50 | 120 |
| 3 | 540 | 20 | 20 |
| 4 | 500 | 10 | 10 |
The code I'm currently using:
DT[,D:= sum(DT$C[A == DT$A & ((B >= DT$B) & (B < DT$B + 20))]), by=c('A', 'B')]
This takes a very long time to actually run, as well as giving me the wrong answer. The output I get looks like this:
| A | B | C | D |
|---|---|---|---|
| 1 | 500 | 10 | 10 |
| 1 | 510 | 20 | 30 |
| 1 | 540 | 10 | 10 |
| 2 | 500 | 20 | 20 |
| 2 | 540 | 10 | 10 |
| 3 | 500 | 50 | 50 |
| 3 | 510 | 20 | 70 |
| 3 | 519 | 50 | 120 |
| 3 | 540 | 20 | 20 |
| 4 | 500 | 10 | 10 |
(i.e. D only appears to increase cumulatively).
I'm less concerned with the cumulative thing, more about speed. Ultimately what I'm trying to get to is the largest sum of C, by A, subject to B being within 20 of eachother. I would really appreciate any help on this! Thanks in advance.