TobKel
TobKel

Reputation: 1453

R STL decomposition of daily tsibble dataframe

I have a dataset from the German Weather Service, consisting of daily temperature measurements, which can be downloaded using the rdwd-package. I want to decompose this time series using the STL method. I have previously converted the weather dataset into a tsibble time-series object.

library(tidyverse)
library(rdwd)
library(seasonal)
library(tsibble)

df <-
  readDWD(dataDWD(
    selectDWD(
      name = "Jena (Sternwarte)",
      res = "daily",
      var = "kl",
      per = "historical"
    ),
    read = FALSE
  ), varnames = TRUE)

df<-df%>%tibble()%>% 
  mutate(MESS_DATUM = as.Date(MESS_DATUM))%>%
  filter(MESS_DATUM>=as.Date("2005-01-01"))%>%
  rename(Temperatur = TMK.Lufttemperatur)

as_tsibble(df, index= MESS_DATUM)%>%
  select(MESS_DATUM,Temperatur)%>%
  stl(s.window = "periodic", robust = T)%>%
  autoplot()

However, I don't really know if the dataset in its current format is suitable for STL decomposition or what parameters I need to set in the stl function for this daily dataset. The trend series should be rather a straighter line and seasonal component is totally distorted.
Can anyone help me with the programming?
Many thanks in advance!

enter image description here

Upvotes: 1

Views: 904

Answers (2)

Rob Hyndman
Rob Hyndman

Reputation: 31800

The stl() function is not designed for tsibble objects. You either need to convert your data to a ts object, as described by @Roland, or use the feasts::STL function like this.

library(tidyverse)
library(rdwd)
library(tsibble)
library(feasts)

as_tsibble(df, index = MESS_DATUM) %>%
  select(MESS_DATUM, Temperatur) %>%
  model(STL(Temperatur ~ season(period = "year"), robust = TRUE)) |>
  components() |>
  autoplot()

Created on 2022-10-26 with reprex v2.0.2

Upvotes: 3

Roland
Roland

Reputation: 132696

I don't speak tidyverse. Your issue looks like the periodicity of your time series is wrong.

df$MESS_DATUM <- as.Date(df$MESS_DATUM)
df <- df[df$MESS_DATUM >= as.Date("2005-01-01"),]
temps <- ts(df$TMK.Lufttemperatur, start = c(2005, 01), frequency = 365)
plot(stl(temps, s.window = "periodic"))

resulting plot with stl decomposition of the time series

This ignores the existence of leap years (which I don't know how to deal with correctly).

Upvotes: 1

Related Questions