Skip to content

Instantly share code, notes, and snippets.

@phil8192
Created June 6, 2016 16:49
Show Gist options
  • Save phil8192/fbe9b439e63c1a8840952dcb2a321507 to your computer and use it in GitHub Desktop.
Save phil8192/fbe9b439e63c1a8840952dcb2a321507 to your computer and use it in GitHub Desktop.
rle sequence replace
oi <- c(0,1,0,0,-1,0,0,1,0,-1,0,0,0,0,0,1,0,0,0,-1,0,0,0)
cs <- cumsum(oi)
# ^-- map: 0 1 1 1 0 0 0 1 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0
# ^-- to: 0 1 1 1 0 0 0 2 2 0 0 0 0 0 0 3 3 3 3 0 0 0 0
(rle.cumsum.trickery <- function(mask) {
rle1 <- rle(mask)
x <- rle1$values
rle1$values <- cumsum(x) * x
inverse.rle(rle1)
})(cs)
# probably a nicer way with diff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment