Skip to content

Instantly share code, notes, and snippets.

@dfsnow
Last active March 18, 2026 08:07
Show Gist options
  • Select an option

  • Save dfsnow/b9bef6b5f9df261c7976c7ff8fed3d52 to your computer and use it in GitHub Desktop.

Select an option

Save dfsnow/b9bef6b5f9df261c7976c7ff8fed3d52 to your computer and use it in GitHub Desktop.
Group cumulative reduce
# 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