[R] aggregate.zoo

Hutchinson,David [PYR] David.Hutchinson at ec.gc.ca
Thu May 13 22:36:03 CEST 2010


Achim,

Thanks for pointing me in the right direction! I broke your user-defined
function down into two separate aggregate calls on which.min and length.


library(zoo)
n <- 1000
dly <- zoo(  x = rnorm(n),   order.by = seq.Date(as.Date('1970-01-01'),
by = 'day', length.out = n)   )
year <- as.numeric( format(index(dly), '%Y') ) 
annual.min <- aggregate( dly, by = year, FUN = min )

ix <- aggregate(dly, year, which.min )
l <- aggregate(dly, year, length)

a <- c(0, as.vector(cumsum(l)[-length(l)]))
b <- as.vector(ix)

annual.min <- dly[a+b]

plot(dly)
points(annual.min, pch = 19, col = 'red')
 

-----Original Message-----
From: Achim Zeileis [mailto:Achim.Zeileis at uibk.ac.at] 
Sent: Thursday, May 13, 2010 12:29 PM
To: Hutchinson,David [PYR]
Cc: r-help at r-project.org
Subject: Re: [R] aggregate.zoo

On Thu, 13 May 2010, Hutchinson,David [PYR] wrote:

> I have been using aggregate function to determine the annual minimum 
> in a daily time series. However, I was also hoping to determine the 
> date of occurrence without having to loop through each year to 
> identify the date of each minimum returned from aggregate(). Is there 
> a more convenient way of doing so?

You could do something like this:

## determine position of minimum and number of observations ix <-
aggregate(dly, year, function(x) c(which.min(x), length(x)))

## expand to overall index
ix <- as.vector(cumsum(c(0, head(ix[,2], -1))) + ix[,1])

## subset original series
dly[ix]

hth,
Z

> Thanks in advance,
>
> Dave
>
> library(zoo)
> n <- 1000
> dly <- zoo(  x = rnorm(n),   order.by =
seq.Date(as.Date('1970-01-01'),
> by = 'day', length.out = n)   )
> year <- as.numeric( format(index(dly), '%Y') ) annual.min <- 
> aggregate( dly, by = year, FUN = min )
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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