Skip to content

Instantly share code, notes, and snippets.

@jgilfillan
Created February 3, 2017 12:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgilfillan/23336d0f5bcfffe6a71d0bdd634d023e to your computer and use it in GitHub Desktop.
Save jgilfillan/23336d0f5bcfffe6a71d0bdd634d023e to your computer and use it in GitHub Desktop.
Cumulative sum in R with reset after reaching threshold
testvector <- c(.5, .1, .2, .9, .9, .2, .5)
# group rows based on cumsum with reset
cumsum_group <- function(x, threshold) {
cumsum <- 0
group <- 1
result <- numeric()
for (i in 1:length(x)) {
cumsum <- cumsum + x[i]
if (cumsum > threshold) {
group <- group + 1
cumsum <- x[i]
}
result = c(result, group)
}
return (result)
}
# cumsum with reset
cumsum_with_reset <- function(x, threshold) {
cumsum <- 0
group <- 1
result <- numeric()
for (i in 1:length(x)) {
cumsum <- cumsum + x[i]
if (cumsum > threshold) {
group <- group + 1
cumsum <- x[i]
}
result = c(result, cumsum)
}
return (result)
}
# test
cumsum_group(testvector, 1)
cumsum_with_reset(testvector, 1)
# read_excel("c:\\Users/jgilf_000/Desktop/cumsum_test.xlsx") %>%
# group_by(var1) %>%
# mutate(group = cumsum_group(val2, 1),
# cumsum = cumsum_with_reset(val2, 1)
# )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment