[R] How do I create a plotable zoo object based on weekly data?

Gabor Grothendieck ggrothendieck at gmail.com
Fri Sep 17 01:22:34 CEST 2010


On Thu, Sep 16, 2010 at 8:50 AM, Michael Green <mig at data-intelligence.dk> wrote:
> Dear readers,
>
> The problem is simple: I have weekly time series data with a maximum
> week number of (52,53,52,52) in (2008,2009,2010,2011) respectively. That
> means I have a dataset looking like this:
>
> 2008-01 value
> 2008-02 value
> .
> .
> 2011-52 value
>
> And I would like to turn that data into a plotable zoo object. Now a
> simple example containing 4 data points, each being on the December
> 28th, would be:
>
> x <- zoo(rnorm(4), as.Date("2008-12-28")+0:3*365)
> plot(x)
>
> This works fine, but
>
> y <- zoo(rnorm(4), format(as.Date("2008-12-28")+0:3*365, "%Y-%U"))
> plot(y)
>
> gives me the following warning message:
>
> Error in plot.window(...) : need finite 'xlim' values In addition:
> Warning messages:
> 1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
> 2: In min(x) : no non-missing arguments to min; returning Inf
> 3: In max(x) : no non-missing arguments to max; returning -Inf
>
> Anyone knows how to solve this?
>

To use a new class of time index you would have to supply an axis
method for that class.  In this case it might be good enough to map it
to numeric (year plus week fraction) like this:


as.yearwk <- function(x) {
	wk <- as.numeric(sub("....-", "", x))
	year <- as.numeric(sub("-..", "", x))
	lastwk <- as.numeric(format(as.Date(sprintf("%s-12-31", year)), "%U"))
	year + (wk - 1) / lastwk
}

library(zoo)

# test data
set.seed(1)
y <- zoo(rnorm(4), format(as.Date("2008-12-28")+0:3*365, "%Y-%U"))

# plot
yy <- y
time(yy) <- as.yearwk(time(yy))
plot(yy)



-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list