0

I have a time series of regular 15 minute data intervals and I want to take a rolling average of the data for every 2 hours, hence the width of the rollmean interval would be 8. The only issue is that the length of the original time series that I put in is 35034, but the length of the data that I get as output is 35027. Is there a way that the length of the output is the same as the input and does have data in it at the end as well. i dont want to fill it with NA's at the end

interval <- 2 #2 hours
data <- data.frame(t=streamflowDateTime,flow=streamflow)
data2hr <- data
rollingWidth <- (interval*60)/15
library(zoo)
smoothedFlow <- rollmean(data2hr$flow,rollingWidth,align="center")
Saadat
  • 51
  • 8
  • 2
    Use `runmean` from `caTools` which is much faster and has an `endrule` argument to do whatever you want with the endpoints. – eddi Feb 12 '15 at 16:10

2 Answers2

1

I am not completely clear on how you want to do the filling but here are some ways:

1) Add the argument fill = NA to rollmean to add NA's to the ends.

2) If you want partial means at the ends then use this where x is your data, width is the number of points to take the mean of each time:

rollapply(x, width, mean, partial = TRUE)

(The points near the ends will be the mean of fewer than width points since, of course, there just aren't that many near the ends.)

3) Assuming width is odd you could pad the input series with (width-1)/2 values (possibly NA depending on what you want) on each end.

4) This keeps the original values near the ends:

out <- rollmean(x, width, fill = NA)
isNA <- is.na(out)
out[isNA] <- x[isNA]

Note: align = "center" is the default for both rollmean and rollapply so that can be omitted.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
0

If you don't want NA, you can use fill parameter for extending the data range with simple constant values:

With keyword "extend" rollmean will extend your input vector:

rollmean(x, k, align="center", fill = "extend")

or define a three component constant for left|at|right:

rollmean(x, k, align="center", fill = c(42, 69, 666))
bergant
  • 7,122
  • 1
  • 20
  • 24