[R] Calculating quarterly statistics for time series object

Gabor Grothendieck ggrothendieck at gmail.com
Sun Jun 29 14:19:43 CEST 2008


See ?aggregate.zoo, ?as.yearqtr and vignette("zoo-quickref") and
the other zoo vignettes.

library(zoo)

SD <- 1
date1 <- seq(as.Date("2001-01-01"), as.Date("2002-12-1"), by = "day")
len1 <- length(date1)
set.seed(1) # to make it reproducible
data1 <- zoo(rnorm(len1), date1)
plot(data1)

# quarterly summary

data1q.mean <- aggregate(data1, as.yearqtr, mean)
data1q.sd <- aggregate(data1, as.yearqtr, sd)
plot(cbind(mean = data1q.mean, sd = data1q.sd), main = "Quarterly")

# weekly summary - week ends on tuesday

# Given a date find the next Tuesday.
# Based on formula in Prices and Returns section of zoo-quickref vignette.
nexttue <- function(x) 7 * ceiling(as.numeric(x - 2 + 4)/7) + as.Date(2 - 4)

data1w <- cbind(
	mean = aggregate(data1, nexttue, mean),
	sd = aggregate(data1, nexttue, sd)
)
head(data1w)
plot(data1w, main = "Weekly")

### ALTERNATIVE ###

# Create function ag like aggregate but takes vector of
# function names.

FUNs <- c(mean, sd)
ag <- function(z, by, FUNs) {
	f <- function(f) aggregate(z, by, f)
	do.call(cbind, sapply(FUNs, f, simplify = FALSE))
}

data1q <- ag(data1, as.yearqtr, c("mean", "sd"))
data1w <- ag(data1, nexttue, c("mean", "sd"))


On Sun, Jun 29, 2008 at 3:17 AM, Megh Dal <megh700004 at yahoo.com> wrote:
> I have time series observation on daily frequencies :
>
> library(zoo)
> SD=1
> date1 = seq(as.Date("01/01/01", format = "%m/%d/%y"), as.Date("12/31/02", format = "%m/%d/%y"), by = 1)
> len1 = length(date1); data1 = zoo(matrix(rnorm(len1, mean=0, sd=SD*0.5), nrow = len1),  date1)
> plot(data1)
>
>
> Now I want to calculate 1. Quarterly statistics like mean, variance etc and 2. Weekly statistics, where as per my definition week starts from Wednesday and ends on Tuesday.
>
> I can define some 'for' loop for doing those. However it takes considerably amount of time. Is there any advance methods in R to do the same?
>
> Regards,
>
>
>
>
>
>
>        [[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