[R] Sweeping a zoo series

Gabor Grothendieck ggrothendieck at gmail.com
Wed Aug 11 21:45:01 CEST 2010


On Wed, Aug 11, 2010 at 2:44 PM, Gabor Grothendieck
<ggrothendieck at gmail.com> wrote:
> On Wed, Aug 11, 2010 at 2:38 PM, steven mosher <moshersteven at gmail.com> wrote:
>> The colMeans comes closest,
>> for a single series the assume you have 100 years of monthly data.
>> The mean you want to scale by is the mean for a restricted period in the
>> center
>> of the series.. say 1950-1960
>> for this period you have the average jan (1950-1960) average feb, ect.
>> your final series would be
>> jan 1900 - average jan(1950-60)
>> feb 1990 - average feb
>> ....
>> jan 2000 - average jan(1950-60)
>> Which gives you a scaling that is not relative to the mean of the whole, but
>> relative to a base period which is selctable.
>> BTW switching to zoo has greatly simplified the code.
>>
>
> Try this to demean by column means for the years 2003 to 2007
> inclusive even though the series extends beyond that in both
> directions:
>
>> z <- zoo(cbind(a = 1:10, b = (1:10)^2), 2001:2010)
>> sweep(z, 2, colMeans(window(z, 2003:2007)))
>      a   b
> 2001 -4 -26
> 2002 -3 -23
> 2003 -2 -18
> 2004 -1 -11
> 2005  0  -2
> 2006  1   9
> 2007  2  22
> 2008  3  37
> 2009  4  54
> 2010  5  73
>

window also has start and end arguments so this works too:

> zz <- zoo(cbind(a = 1:10, b = (1:10)^2), as.yearmon(2000 + 0:9/12))

> colMeans. <- colMeans(window(zz, start = as.yearmon(2000+2/12), end = as.yearmon(2000 + 6/12)))
> sweep(zz, 2, colMeans.)
          a   b
Jan 2000 -4 -26
Feb 2000 -3 -23
Mar 2000 -2 -18
Apr 2000 -1 -11
May 2000  0  -2
Jun 2000  1   9
Jul 2000  2  22
Aug 2000  3  37
Sep 2000  4  54
Oct 2000  5  73

> # and the start and end args are coerced to the index class so it
> # can be shortened to:
>
> colMeans. <- colMeans(window(zz, start = 2000+2/12, end = 2000 + 6/12))
> sweep(zz, 2, colMeans.)
          a   b
Jan 2000 -4 -26
Feb 2000 -3 -23
Mar 2000 -2 -18
Apr 2000 -1 -11
May 2000  0  -2
Jun 2000  1   9
Jul 2000  2  22
Aug 2000  3  37
Sep 2000  4  54
Oct 2000  5  73



More information about the R-help mailing list