[R] Finding seasonal peaks in a time series....

Andy Bunn abunn at whrc.org
Thu Jan 13 18:26:21 CET 2005


This is inelegant, but works:

# (following the example)
nPts <- 254
foo <- sin((2 * pi * 1/24) * 1:nPts)
foo <- foo + rnorm(nPts, 0, 0.05)
bar <- ts(foo, start = c(1980,3), frequency = 24)
mean.in.i <- numeric(length(start(bar)[1]:end(bar)[1]))
peak.ts   <- ts(rep(NA, length(foo)), start = c(1980,3), frequency = 24)
count <- 1
for(i in start(bar)[1]:end(bar)[1]){
      bar.win <- window(bar, start = c(i,1), end = c(i,24))
      max.in.i <- max(bar.win)
      max.cycle.in.i <- cycle(bar.win)[bar.win == max.in.i]
      mean.in.i[count] <- mean(window(bar, start = c(i,max.cycle.in.i - 3),
end = c(i,max.cycle.in.i + 3)))
      window(peak.ts, start = c(i, max.cycle.in.i), end = c(i,
max.cycle.in.i)) <- mean.in.i[count]
      count <- count+1
}
plot(bar)
points(peak.ts, col = "red", pch = "+")
mean.in.i



> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch]On Behalf Of Dr Carbon
> Sent: Wednesday, January 12, 2005 5:19 PM
> To: r-help at stat.math.ethz.ch
> Subject: [R] Finding seasonal peaks in a time series....
>
>
>  I have a seasonal time series. I want to calculate the annual mean
> value of the time series at its peak
>
>  (say the mean of the three values before the peak, the peak, and the
> three values after the peak).
>
>  The peak of the time series might change cycle slightly from
> year to year.
>
> # E.g.,
> nPts <- 254
> foo <- sin((2 * pi * 1/24) * 1:nPts)
> foo <- foo + rnorm(nPts, 0, 0.05)
> bar <- ts(foo, start = c(1980,3), frequency = 24)
> plot(bar)
> start(bar)
> end(bar)
>
> # I want to find the peak value from each year, and then get the mean
> of the values on either side.
> # So, if the peak value in the year 1981 is
> max.in.1981 <- max(window(bar, start = c(1981,1), end = c(1981,24)))
> # e.g, cycle 7 or 8
> window(bar, start = c(1981,1), end = c(1981,24)) == max.in.1981
> # E.g. if the highest value in 1981 is in cycle 8 I want
> mean.in.1981 <- mean(window(bar, start = c(1981,5), end = c(1981,11)))
> plot(bar)
> points(ts(mean.in.1981, start = c(1981,8), frequency = 24), col =
> "red", pch = "+")
>
>
>  Is there a way to "automate" this for each year.
>
>  How can I return the cycle of the max value by year?
>
>  Thanks in advance. -DC
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html




More information about the R-help mailing list