[R] Computing Time Intervals On A Series

David Winsemius dwinsemius at comcast.net
Fri Jul 3 16:39:55 CEST 2009


I noticed that Gabor's interpretation of your desires was the opposite  
of what mine was, and also that you were thinking tapply might be a  
useful strategy. Here is a tapply implementation that lets you choose:

x$wanted <- c(0,-diff(x$status))
x$dif.tm <- c(diff(x$time),NA)
sum(x[x$wanted==1, "dif.tm"], na.rm=TRUE)
# [1] 43

  with( x, tapply(dif.tm, wanted, sum, na.rm=TRUE) )

# -1  0  1
# 26  6 43


On Jul 3, 2009, at 9:21 AM, rory.winston at gmail.com wrote:

> Hi
>
> I have a dataset that looks like this (dput'd below):
>
>> head(x, 20)
>
> time status
> 1 2009-07-02 10:32:37 1

> snip
> I would like to be able to calculate the total time spent in state  
> 0, in
> other words
> the diff of the times of x where x$status changes from 0 to 1. I've  
> been
> struggling
> with tapply() to do this, but without huge success....anyone know an
> elegant way
> to do this?
>
> Cheers
> -- Rory
>
> structure(list(time = structure(c(1246527157, 1246527163, 1246527163,
> 1246527164, 1246527164, 1246527168, 1246527168, 1246527174,  
> 1246527184,
> 1246527184, 1246527185, 1246527187, 1246527193, 1246527197,  
> 1246527220,
> 1246527228, 1246527230, 1246527231, 1246527232, 1246527232), class =
> c("POSIXt",
> "POSIXct"), tzone = ""), status = c(1, 0, 1, 0, 1, 0, 1, 0, 1,
> 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0)), .Names = c("time", "status"
> ), row.names = c(NA, 20L), class = "data.frame")

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list