Last active
March 18, 2026 08:07
-
-
Save dfsnow/b9bef6b5f9df261c7976c7ff8fed3d52 to your computer and use it in GitHub Desktop.
Group cumulative reduce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # https://stackoverflow.com/questions/40412516/how-to-write-a-cumulative-calculation-in-data-table | |
| library(dplyr) | |
| library(data.table) | |
| dt <- tribble( | |
| ~"a", ~"b", ~"g", | |
| 0.03, 3340, "B", | |
| 0.03, NA, "B", | |
| 0, NA, "B", | |
| 0.05, NA, "B", | |
| 0, NA, "B", | |
| 0.03, 3502, "D", | |
| 0.03, NA, "D", | |
| 0, NA, "D", | |
| 0.05, NA, "D", | |
| 0.02, NA, "D" | |
| ) | |
| setDT(dt) | |
| dt[, | |
| z := Reduce( | |
| f = function(v, i) round(v / sum(1, a[i], na.rm = TRUE)), | |
| x = seq_len(.N)[-1], | |
| init = b[1], | |
| accumulate = TRUE | |
| ), | |
| by = .(g) | |
| ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment