Skip to content
Prev 4776 / 15274 Next

Aggregating irregular time series

Try this for the first question:

neighborapply <- function(z, width, FUN) {
	out <- z
	ix <- seq_along(z)
	jx <- findInterval(time(z) + width, time(z))
	out[] <- mapply(function(i, j) FUN(c(0, z[seq(i+1, length = j-i)])), ix, jx)
	out
}

# test - corrected :948 in last line

library(zoo)
library(chron)

Lines <- "Time                              x
10:00:00.021                20
10:00:00.224                20
10:00:01.002                19
10:00:02.948                20"

z <- read.zoo(textConnection(Lines), header = TRUE, FUN = times)

neighborapply(z, times("00:00:02"), sum)

# and here is an alternative neighborapply
# using loops.  The non-loop solution does
# have the disadvantage that it does as
# readily extend to other situations which
# is why we add this second solution to
# the first question.

neighborapply <- function(z, width, FUN) {
	out <- z
	tt <- time(z)
	for(i in seq_along(tt)) {
		for(j in seq_along(tt)) {
			if (tt[j] - tt[i] > width) break
		}
		if (j == length(tt) && tt[j] - tt[i] <= width) j <- j+1
		out[i] <- FUN(c(0, z[seq(i+1, length = j-i-1)]))
	}
	out
}

The second question can be answered along the lines
of the first by modifying neighborapply in the loop solution
appropriately.
On Sun, Aug 30, 2009 at 9:38 PM, R_help Help<rhelpacc at gmail.com> wrote: