0

I have a zoo obj like that colled z.

> z["2013-12",1]
       Allerona

2013-12-01 0.0 2013-12-02 0.0 2013-12-03 0.0 2013-12-04 0.0 2013-12-05 0.2 2013-12-06 0.0 2013-12-07 0.0 2013-12-08 0.2 2013-12-09 0.0 ....

It stores daily value of rainfall.

I'm able to compute the 5-days accumulation using rollapply usingi:

m=rollapply(z, width=3, FUN=sum, by=1, by.column=TRUE, fill=NA, align="right")

It looks ok

> m["2013-12",1] Allerona 2013-12-01 0.0 2013-12-02 0.0 2013-12-03 0.0 2013-12-04 0.0 2013-12-05 0.2 2013-12-06 0.2 2013-12-07 0.2 2013-12-08 0.2 2013-12-09 0.2 ...

How can I calculate for each day themean for 5-years before?

Thanks

2 Answers2

0
SMA (x, n=5*365) 

does not do the trick ?

R.S.
  • 2,093
  • 14
  • 29
  • 1
    I don't know such function. In R base is no present. Where I can find it? Thanks – pierluigi de rosa Jul 22 '15 at 17:15
  • It's in the TTR package. I assumed if you were using zoo, you were probably also using XTS and TTR. Anyway you can install xts and get loads of Time Series functions – R.S. Jul 22 '15 at 17:19
  • I tried. I obtain: `> SMA(m,n = 5*365) Error in runSum(x, n) : not enough non-NA values ` – pierluigi de rosa Jul 22 '15 at 17:25
  • There seems to be lots of missing data for earlier periods. You will need some strategy to fill them. You can check ?na.fill . Anyway, it seems Moving Averages are what you are looking for. You can calculate SMAs for shorter periods and see if they work the way you wanted. Then worry about the missing data. – R.S. Jul 22 '15 at 17:43
0

I sorted my problem. The solution was to use a list into the width parameter of rollapply. here below the code:

mean5year=rollapply(as.zoo(m), list(-365*5:1), function(x) {mean(x,na.rm = TRUE)},fill=NA)

where

list(-365*5:1)

takes the same day but in the previous 5-years. I should also use a mean with na.rm =TRUE to compute mean also if NA are in the sequence