Skip to content

Instantly share code, notes, and snippets.

@mrdwab
Last active January 4, 2016 09:19
Show Gist options
  • Save mrdwab/8601445 to your computer and use it in GitHub Desktop.
Save mrdwab/8601445 to your computer and use it in GitHub Desktop.
TrueSeq <- function(inLogi, zero2NA = FALSE) {
x <- rle(cumsum(!inLogi)[inLogi])$lengths
inLogi[inLogi] <- rep(seq_along(x), x)
if (isTRUE(zero2NA)) inLogi[inLogi == 0] <- NA
inLogi
}
@mrdwab
Copy link
Author

mrdwab commented Jan 24, 2014

Example:

set.seed(1)
x <- sample(c(TRUE, FALSE), 1e6, TRUE)

JB <- function(x) {
  A <- cumsum(!x)
  factor(ifelse(x, A, NA), labels = seq_along(unique(A[x])))
} 

TrueSeq <- function(inLogi, zero2NA = FALSE) {
  x <- rle(cumsum(!inLogi)[inLogi])$lengths
  inLogi[inLogi] <- rep(seq_along(x), x)
  if (isTRUE(zero2NA)) inLogi[inLogi == 0] <- NA
  inLogi
}    

system.time(outJB <- JB(x))
#    user  system elapsed 
#   1.671   0.028   1.709 
system.time(outTS <- TrueSeq(x, zero2NA=TRUE))
#    user  system elapsed 
#   0.318   0.012   0.335 
system.time(outTSF <- TrueSeq(x))
#    user  system elapsed 
#   0.190   0.000   0.195 

all.equal(as.numeric(as.character(outJB)), outTS)
# [1] TRUE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment