[R] subsetting, aggregating and zoo

Gabor Grothendieck ggrothendieck at gmail.com
Sat Oct 28 22:37:20 CEST 2006


Try this:

# test data
x <- c(1:4, 6:8, 10:14)
z <- zoo(x, as.Date(x))

# idx is 1 for first run, 2 for second run, etc.
idx <- cumsum(c(1, diff(z) != 1))

# starts replaces each time with the start time of that run
# ends is similar but for ends
starts <- time(z)[match(idx, idx)]
ends <- time(z)[cumsum(table(idx))[idx]]

# average over each run using the time of the end of run for the result
# replace ends with starts if that is preferred
aggregate(z, ends, mean)


On 10/28/06, antonio rodriguez <antonio.raju at gmail.com> wrote:
> Gabor Grothendieck escribió:
> > On 10/28/06, antonio rodriguez <antonio.raju at gmail.com> wrote:
> >> Hi,
> >>
> >> Having an zoo object I can subset it to obtain the days where I have the
> >> values within some range:
> >>
> >> is.zoo(z)
> >> TRUE
> >>
> >> subset(z[,1], z[,1]>=5 & z[,1]<= 10) #Yields: Year(day)
> >>
> >> 1988(13)  1988(14)  1988(16)  1988(20)  1988(21)  1988(22)  1988(25)
> >> 1988(26)
> >> 7.973946  9.933518  7.978227  7.512960  6.641862  5.667780  5.721358
> >> 6.863729
> >> 1988(27)  1988(28)  1988(29)  1988(30)  1988(32)  1988(33)  1988(34)
> >> 1988(35)
> >>  9.600000  9.049846  9.213438  6.412746  5.543606  7.881596  6.373102
> >> 7.220562
> >> ..................................................................................................................
> >>
> >> ..................................................................................................................
> >>
> >>
> >> How do I could refine the search in order to obtain those consecutive
> >> days within a specific range? In the above extract:
> >>
> >> 1988(26) 1988(27)  1988(28)  1988(29)  1988(30)  1988(33)  1988(34)
> >> 1988(35)
> >>  6.863729 9.600000  9.049846  9.213438  6.412746  7.881596  6.373102
> >> 7.220562
> >>
> >
> > If zz is a zoo series time(zz) or equivalently index(zz) gives the times.
>
> But how to aggregate, for example, 4 consecutive days with that range of
> values? I've played with aggregate(z,index(z), ...) but I can't find the
> right FUN to do this
>
> Thanks in advance,
>
> Antonio
>
>



More information about the R-help mailing list