Starbucks Starbucks - 4 months ago 29
R Question

STL Time Series Output - Creating new vector - R

Is it possible to save the output from an STL analysis into vectors?

> stl(satat.ts, s.window = 4)
Call:
stl(x = satat.ts, s.window = 4)

Components
seasonal trend remainder
2015 Q1 -169.91957477 2914.934 137.98532
2015 Q2 11.37099404 3155.224 15.40541
2015 Q3 0.09573424 3395.513 -125.60867
2015 Q4 165.60565883 3636.489 -132.09422
2016 Q1 -184.86967286 3877.464 -68.59450
2016 Q2 -10.47226510 4125.118 121.35381
2016 Q3 25.14061969 4372.773 115.08665
2016 Q4 196.59890247 4593.852 33.54917
2017 Q1 -198.92478464 4814.931 58.99366
2017 Q2 -45.81852354 5031.778 -123.95919
2017 Q3 42.63407915 5248.624 -16.25838
2017 Q4 229.27354553 5461.215 27.51108


I would like to create a vector of the trend. How would I go about doing that without manually typing each value (i.e. Trend_data <- stl(satat.ts$trend))

Thank you!

Answer

Sure, just assign it. I don't have your data, so I'll use the example at the bottom of ?stl:

stllc <- stl(log(co2), s.window = 21)

Let's see what's there:

str(stllc)
# List of 8
#  $ time.series: mts [1:468, 1:3] -0.000185 0.00173 0.00367 0.007019 0.00869 ...
#   ..- attr(*, "dimnames")=List of 2
#   .. ..$ : NULL
#   .. ..$ : chr [1:3] "seasonal" "trend" "remainder"
#   ..- attr(*, "tsp")= num [1:3] 1959 1998 12
#   ..- attr(*, "class")= chr [1:3] "mts" "ts" "matrix"
#  $ weights    : num [1:468] 1 1 1 1 1 1 1 1 1 1 ...
#  $ call       : language stl(x = log(co2), s.window = 21)
#  $ win        : Named num [1:3] 21 21 13
#   ..- attr(*, "names")= chr [1:3] "s" "t" "l"
#  $ deg        : Named int [1:3] 0 1 1
#   ..- attr(*, "names")= chr [1:3] "s" "t" "l"
#  $ jump       : Named num [1:3] 3 3 2
#   ..- attr(*, "names")= chr [1:3] "s" "t" "l"
#  $ inner      : int 2
#  $ outer      : int 0
#  - attr(*, "class")= chr "stl"

The "time series" sounds promising, check it out:

str(stllc$time.series)
 # mts [1:468, 1:3] -0.000185 0.00173 0.00367 0.007019 0.00869 ...
 # - attr(*, "dimnames")=List of 2
 #  ..$ : NULL
 #  ..$ : chr [1:3] "seasonal" "trend" "remainder"
 # - attr(*, "tsp")= num [1:3] 1959 1998 12
 # - attr(*, "class")= chr [1:3] "mts" "ts" "matrix"

Okay, so it's a matrix and one of the columns is named "trend".

my_trend = stllc$time.series[, "trend"]

Looks good!

Note that we could also read the documentation to help on the way. ?stl says:

stl returns an object of class "stl" with components

time.series: a multiple time series with columns seasonal, trend and remainder.

...

which would lead us to the same result.

Comments