Skip to content

Instantly share code, notes, and snippets.

@zmjones zmjones/decay.R
Last active Oct 12, 2015

Embed
What would you like to do?
time since event and decaying cumulative sums for binary time series
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)
}
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
You can’t perform that action at this time.