[R] max and min with the indexes in a zoo object (or anything else that could solve the problem)

Gabor Grothendieck ggrothendieck at gmail.com
Fri Aug 22 00:23:18 CEST 2008


Perform rollapply over the index rather than the series itself:  The
result, sin.mx is a zoo series with three columns: the original
series, the series of maxima and their index into the original series.


library(zoo)
library(chron)
t1 <- chron("1/1/2006", "00:00:00")
t2 <- chron("1/31/2006", "23:45:00")
deltat <- times("00:15:00")
tt <- seq(t1, t2, by = times("00:15:00"))
d <- sample(33:700, 2976, replace=TRUE)
sin.zoo <- zoo(d,tt)

f <- function(idx) idx[which.max(sin.zoo[idx])]
mx.idx <- rollapply(zoo(seq_along(sin.zoo)), 96, f, na.pad = TRUE)
sin.mx <- zoo(coredata(sin.zoo)[mx.idx], time(sin.zoo))

Another possibility is to encode the indexes into the original series.
This one is faster as it uses the optimized rollmax:

sin.zoo.2 <- sin.zoo + seq_along(sin.zoo) / 10000
mx <- rollmax(sin.zoo.2, 96)
sin.mx.2 <- cbind(sin.zoo, floor(mx), 10000 * (mx - floor(mx)))

On Thu, Aug 21, 2008 at 5:48 PM, stephen sefick <ssefick at gmail.com> wrote:
> library(zoo)
> library(chron)
> t1 <- chron("1/1/2006", "00:00:00")
> t2 <- chron("1/31/2006", "23:45:00")
> deltat <- times("00:15:00")
> tt <- seq(t1, t2, by = times("00:15:00"))
> d <- sample(33:700, 2976, replace=TRUE)
> sin.zoo <- zoo(d,tt)
>
> #there are ninety six reading in a day
> d.max <- rollapply(sin.zoo, width=96, FUN=max)
> d.min <- rollapply(sin.zoo, width=96, FUN=max)
>
> this is about what I would like to do.  I want to be able to get the
> max for one day and then also get the index that coincides with this
> max time period.  Also, the same thing with the min.  With the real
> data I am trying to find out at what time the maximum dissolved oxygen
> value is for each day.
>
> Thanks
>
> --
> Stephen Sefick
> Research Scientist
> Southeastern Natural Sciences Academy
>
> Let's not spend our time and resources thinking about things that are
> so little or so large that all they really do for us is puff us up and
> make us feel like gods. We are mammals, and have not exhausted the
> annoying little problems of being mammals.
>
>        -K. Mullis
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list