Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seasonal decompose of monthly data including NA in r

Tags:

r

na

time-series

I need help to decompose my monthly data which have seasonality, but it does not work because NA values are not removed. There may be another problem. Please look at my data and errors as below.

    ts.monthly<-ts(monthly$rBC.median, frequency=12, start=c(2006, 4))
    ts.monthly
        Jan        Feb        Mar        Apr        May        Jun
    2006                                   5.1656479  6.2847959 19.4833690
    2007  1.4252665  2.9127775  2.8912652  7.5326158  8.6182227 23.2129310
    2008         NA  1.8200842  1.3488755  2.0700927  5.3541366  8.6916708
    2009  1.2531161  1.5075780  2.4955524 10.6724704 10.1367162 16.0362127
    2010  0.8850190  2.4974866  1.8459976  9.2297697  3.8203789  7.1492986
    2011  2.6990434  0.4570701  1.3787403  5.8739804  4.1669501 13.2228535
    2012         NA  2.0670538  1.3758499 11.7306663  4.1248775 12.3604423
                Jul        Aug        Sep        Oct        Nov        Dec
    2006  9.8028986  7.8167810  2.1333807  2.5777504  1.9022561  2.7254065
    2007  4.2121577  8.8604768 12.0017155  4.0978332  1.6053110         NA
    2008  5.7338211  9.7432563  4.6548508  1.3589789  0.9650082  1.2788504
    2009 11.7632775 11.2299683  1.6229679  1.0333217  1.0481580  1.0734208
    2010  3.5996501  4.3245873  4.4586863  1.6403104  2.8622518  1.2564256
    2011  3.0463918  7.1515472  6.5613683  1.3715623  1.9757217  5.4901524
    2012 11.1010563  3.6220968  2.2597341  

   ts.monthly=na.omit(ts.monthly)  
    Error in na.omit.ts(ts.monthly) : time series contains internal NAs
   ts.monthly.com<-decompose(ts.monthly)
    Error in na.omit.ts(x) : time series contains internal NAs
   ts.monthly$seasonal
    Error in ts.monthly$seasonal : $ operator is invalid for atomic vectors

I do not understand why na.omit does not work. How can I treat this NA??

Finally, after using a function "decompose", I want to take only "trend" without seasonality, and then apply sen's slope estimator to get a slope for linear trend. Will it work?

Thanks a lot for your help.

like image 421
user2928318 Avatar asked Jul 11 '14 09:07

user2928318


1 Answers

I struggled with this for a long time too.

Just use na.locf from the zoo package on your ts object. na.locf returns a ts object, so there are no worries about a changed object type.

Use:

    library(zoo)
    season_ts <- na.locf(season_ts)

where season_ts is your ts object.

like image 161
Rishabh Avatar answered Oct 24 '22 21:10

Rishabh