rtime-seriesmissing-dataimputets

R: ts() with NA data


I have following function:

ts.dat <- ts(data=dat$sales, start = 1, frequency = 12)

ts. dat returns

   Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec
1 9000 8600 8500 8600 8500 8300 8600 9100 8800 8700 9300 7900
2 7900 8800 8500 8900 9000 8800 8800 9100 9500 8900 9200 8400
3 8400 9200 9500 9100 8700 8300   NA

However,

 plot(stl(ts.dat, s.window=12))

returns

Error in na.fail.default(as.ts(x)) : missing values in object'plot':

I tried na.action=na.pass, but it didn't work. Any idea how to deal with the NA, if that is the reason?

Also: Any chance to take the first date from dat as the start?


Solution

  • Any idea how to deal with the NA, if that is the reason?

    You need to use na.action = na.omit, i.e., dropping NA when doing computation.

    plot(stl(ts.dat, s.window=12, na.action = na.omit))
    

    stl

    The na.pass will simply assume NA as normal observation. But it will still produce error as stl() later calls compiled code and can not recognize NA.

    Any chance to take the first date from dat as the start?

    Have a look at the examples at the bottom of ?ts:

     ## Using July 1954 as start date:
     gnp <- ts(cumsum(1 + round(rnorm(100), 2)),
               start = c(1954, 7), frequency = 12)
    

    To start from July 1954, put start = c(1954, 7).