Skip to content
Prev 300391 / 398503 Next

Script help: Determining Time Difference between two data points.

By the way, here is a related function I wrote in response to an R-help question
a while back that finds sequences that start when a signal rises about a certain
threshold and end when the signal drops below a lower threshold.  This avoids
hysteresis-like problems.

f1 <- function(x, startThreshold, stopThreshold, plot=FALSE) {
    # find intervals that
    #  start when x goes above startThreshold and
    #  end when x goes below stopThreshold.
    # Return the positions in x of the start and end points of each interval.
    stopifnot(startThreshold > stopThreshold)
    isFirstInRun <- function(x)c(TRUE, x[-1] != x[-length(x)])
    isLastInRun <- function(x)c(x[-1] != x[-length(x)], TRUE)
    isOverStart <- x >= startThreshold
    isOverStop <- x >= stopThreshold
    possibleStartPt <- which(isFirstInRun(isOverStart) & isOverStart)
    possibleStopPt <- which(isLastInRun(isOverStop) & isOverStop)
    pts <- c(possibleStartPt, possibleStopPt)
    names(pts) <- rep(c("start","stop"),
      c(length(possibleStartPt), length(possibleStopPt)))
    pts <- pts[order(pts)]
    tmp <- isFirstInRun(names(pts))
    start <- pts[tmp & names(pts)=="start"]
    stop <- pts[tmp & names(pts)=="stop"]
    # Remove case where first downcrossing happens
    # before first upcrossing.
    if (length(stop) > length(start)) stop <- stop[-1]

    if (plot) {
        plot(x, cex=.5)
        abline(h=c(startThreshold, stopThreshold))
        abline(v=start, col="green")
        abline(v=stop, col="red")
    }
    data.frame(start=start, stop=stop)
}

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com