Last active
October 12, 2015 00:27
-
-
Save zmjones/3943388 to your computer and use it in GitHub Desktop.
time since event and decaying cumulative sums for binary time series
This file contains 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
decay <- function(yvar, d) { | |
# yvar: a binary variable | |
# d: number of periods | |
# returns: the cumulative sum of yvar at each point | |
# where each addition to the count decays away after d periods | |
yvar[is.na(yvar)] <- 0 | |
run <- cumsum(yvar) | |
tvar <- seq_along(yvar) | |
run <- 0 | |
sum <- 0 | |
for(i in 1:length(tvar)) { | |
if(yvar[i] == 1) | |
run <- run + 1 | |
if(run != 0) { | |
event.idx <- which(yvar == 1) | |
for(j in 1:length(event.idx)) { | |
if(i == (d + event.idx[j])) | |
run <- run - 1 | |
}} | |
sum[i] <- run | |
} | |
return(sum) | |
} |
This file contains 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
tse <- function(yvar, tvar = seq_along(yvar)) { | |
if (!(is.numeric(yvar) | is.logical(yvar))){ | |
stop("yvar must be either numeric or logical") | |
} | |
yvar[is.na(yvar)] <- 0 | |
event.idx <- which(yvar == 1) #Find index positions for events | |
run <- cumsum(yvar) #calculate sum up until each index point, returns vector | |
un <- unique(run) #unique values of run variable | |
tlist <- list() | |
for (i in 1:length(un)){ #loop over unique values of run | |
v <- un[[i]] | |
y <- yvar[run == v] | |
t <- tvar[run == v] | |
t <- t - t[1] | |
tlist[[i]] <- t | |
} | |
timeAfterEvent <- unlist(tlist) | |
timeAfterEvent[run == 0] <- NA | |
run[run == 0] <- NA | |
return(timeAfterEvent) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment