R: using stl() on an xts object

2019-08-15 15:13发布

问题:

I'm relatively new to R so please bear with me. I'm trying to get to grips with basic irregular time-series analysis.

That's what my data file looks like, some 40k lines. The spacing is not always exactly 20sec.

Time, Avg
04/03/2015 00:00:23,20.24
04/03/2015 00:00:43,20.38
04/03/2015 00:01:03,20.53
04/03/2015 00:01:23,20.54
04/03/2015 00:01:43,20.53

 data <- read.zoo("data.csv",sep=",",tz='',header=T,format='%d/%m/%Y %H:%M:%S')

I'm happy to aggregate by minutes

data <- to.minutes(as.xts(data))

Using the "open" column as an example

head(data[,1])
                    as.xts(data).Open
2015-03-04 00:00:43             20.24
2015-03-04 00:01:43             20.53
2015-03-04 00:02:43             20.47
2015-03-04 00:03:43             20.38
2015-03-04 00:04:43             20.05
2015-03-04 00:05:43             19.84

data <- data[,1]

And here is where it all falls apart for me

fit <- stl(data, t.window=15, s.window="periodic", robust=TRUE)
Error in stl(data, t.window = 15, s.window = "periodic", robust = TRUE) : 
series is not periodic or has less than two periods

I've googled the error message, but it's not really clear to me. Is period = frequency? For my dataset I would expect the seasonal component to be weekly.

frequency(data) <- 52
fit <- stl(data, t.window=15, s.window="periodic", robust=TRUE)                   
Error in na.fail.default(as.ts(x)) : missing values in object

?

head(as.ts(data))
[1] 20.24    NA    NA    NA    NA    NA

Uh, what?

What am I doing wrong? How do I have to prepare the xts object to be able to properly pass it to stl()?

Thank you.

回答1:

I extract numeric values of xts_object and build a ts object for stl function. However the time stamps of xts_object is completely ignored in this case.

stl(ts(as.numeric(xts_object), frequency=52), s.window="periodic", robust=TRUE)