# [R] loop avoiding on time interval intersects

Olivier Collignon olivier at loudcloud.com
Thu Mar 6 02:02:37 CET 2003

```I am trying to optimize some code to take advantage of R loop-avoiding
capabilities when working on vectors/arrays that contain time intervals.

The calculation involves adding (for each time interval) the time portion
(of events defined by their start and end times) that elapsed during time
intervals.

Any advice on how to improve this code. I searched the email archive and
looked at the MASS book but did not find anything specific that relate to
that.

Not sure how t/sapply could be used here?

Thanks

Olivier Collignon
Principal, Service Level and Risk Management
EDS / Loudcloud Automated Operations

Here is the non-optimized code:
library(chron)

# create an object populated with 3 events and their start and end
timestamps
dts <- dates(c("01/01/2003", "01/02/2003", "01/03/2003", "01/04/2003",
"01/03/2003","01/06/2003"))
tms <- times(c("23:00:00", "22:00:00", "01:00:00", "18:00:00", "16:00:00",
"01:00:00"))
events <- array(chron(dates = dts, times = tms),c(3,2))

# create an object with 2 consecutive intervals (regular or not)
dts2 <- dates(c("01/01/2003", "01/03/2003", "01/03/2003", "01/06/2003"))
tms2 <- times(c("0:0:0", "0:0:0", "0:0:0", "0:0:0"))
interv <- array(chron(dates = dts2, times = tms2),c(2,2))

fnIntersect <- function(events,interv)
{
overlp <- numeric()

n <- dim(events)[1]
m <- dim(interv)[1]

# perform the query to get the overlapping elapsed time between the events
and the intervals
# returns a vector with the time intervals and the sum of the intersecting
times from the 'event' input

# intervals: +--------+--------+--------+
# events:        +1234567890+
#                    +1234+
#                    +12345678901+
#                        +1234+
#                          +1234567890+
#
#
# summing the overlaps for each interval (e.g number of minutes)
# intervals: +--------+--------+--------+
#            5+1+1    6+4+9+5+4 2+7
#            =        =         =
#            6        28        9
# loop over each interval
for (j in 1:m)
{
overlp[j] <- 0
# loop over each event
for (i in 1:n)
{
# for events ending after the start of the interval
if (events[i,2] >= interv[j,1])
{
# for events starting before the end of the interval
if (events[i,1] <= interv[j,2])
{
# add the time that elapsed during the interval across all events
overlp[j] <- overlp[j] + abs( min(interv[j,2],events[i,2]) -
max(interv[j,1],events[i,1]) )
}
}
}
}
# output has 3 colums: start of interval, end of interval, sum of
overlapping time from events
overlp <- cbind(interv, overlp)

```