Time averaging (sliding window) of columns in data.frame

I have a data.frame that has multiple columns. One of the columns is time and therefore does not decrease. The remaining columns contain the observations recorded at the point in time specified in the specified data.frame row.

I want to select a time window, say “x” seconds, and calculate the average (or, if there is, any function) record in some other columns in the same file. File for this window.

Of course, since its average value over time, the number of entries in the window may vary depending on the data. This is due to the fact that the number of lines belonging to a particular time window can vary.

I did this using a custom function that creates a new column in data.frame. The new column assigns to one element all the entries in the time window. The number is unique in all time windows. This essentially divides the data into groups based on time windows. Then I use the R population function to calculate the average.

I'm just wondering if there is an existing R function that can perform grouping based on a time interval or if there is a better (cleaner) way to do this.

+5
source share
1 answer

Assuming yours data.framecontains only numeric data, this is one way to do this with 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: R. , , endpoints 5- . 5- , = 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
+4

All Articles