Time-based averaging (sliding window) of columns in a data.frame
Assuming your data.frame
contains only numeric data, this is one way to do it using zoo/xts:
> Data <- data.frame(Time=Sys.time()+1:20,x=rnorm(20))
> xData <- xts(Data[,-1], Data[,1])
> period.apply(xData, endpoints(xData, "seconds", 5), colMeans)
[,1]
2010-10-20 13:34:19 -0.20725660
2010-10-20 13:34:24 -0.01219346
2010-10-20 13:34:29 -0.70717312
2010-10-20 13:34:34 0.09338097
2010-10-20 13:34:38 -0.22330363
EDIT: using only base R packages. The means are the same, but the times are slightly different because endpoints
starts the 5-second interval with the first observation. The code below groups on 5-second intervals starting with seconds = 0.
> nSeconds <- 5
> agg <- aggregate(Data[,-1], by=list(as.numeric(Data$Time) %/% nSeconds), mean)
> agg[,1] <- .POSIXct(agg[,1]*nSeconds) # >= R-2.12.0 required for .POSIXct