Exercise 2.1

Explore these four time series:

Bricks from aus_production Lynx from pelt Close from gafa_stock Demand from vic_elec

Determine the time interval for each series, create a time plot using autoplot(), and change the title and axis labels for the final plot.

install.packages("fpp3")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.6'
## (as 'lib' is unspecified)
library(fpp3)
## ── Attaching packages ──────────────────────────────────────────── fpp3 1.0.3 ──
## ✔ tibble      3.3.1     ✔ tsibble     1.2.0
## ✔ dplyr       1.2.1     ✔ tsibbledata 0.4.1
## ✔ tidyr       1.3.2     ✔ ggtime      1.0.0
## ✔ lubridate   1.9.5     ✔ feasts      0.5.0
## ✔ ggplot2     4.0.3     ✔ fable       0.5.0
## ── Conflicts ───────────────────────────────────────────────── fpp3_conflicts ──
## ✖ lubridate::date()    masks base::date()
## ✖ dplyr::filter()      masks stats::filter()
## ✖ tsibble::intersect() masks base::intersect()
## ✖ tsibble::interval()  masks lubridate::interval()
## ✖ dplyr::lag()         masks stats::lag()
## ✖ tsibble::setdiff()   masks base::setdiff()
## ✖ tsibble::union()     masks base::union()
aus_production |>
  autoplot(Bricks)
## Warning: Removed 20 rows containing missing values or values outside the scale range
## (`geom_line()`).

pelt |>
  autoplot(Lynx)

gafa_stock |>
  autoplot(Close)

vic_elec |>
  autoplot(Demand) +
  labs(
    title = "Victoria Electricity Demand",
    x = "Time",
    y = "Demand"
  )

The four datasets use different time intervals. The Bricks data is quarterly, the Lynx data is annual, the stock price data is recorded on trading days, and the electricity demand data is recorded every 30 minutes.

The Bricks data shows changes in brick production over time with a seasonal pattern. The Lynx data has large increases and decreases over several years. The stock prices change over time and generally show longer-term trends rather than a regular seasonal pattern. The electricity demand data has strong repeating patterns because electricity usage changes throughout the day.

Exercise 2.2

Using the gafa_stock dataset, use filter() to determine the date when each of the four stocks reached its highest closing price.

gafa_stock |>
  group_by(Symbol) |>
  filter(Close == max(Close)) |>
  select(Symbol, Date, Close)

The code groups the observations by stock and finds the highest closing price for each company. These dates represent the highest closing price recorded for each stock in the dataset.

Exercise 2.3

Download the tute1.csv dataset containing quarterly Sales, Advertising Budget, and GDP data. Read the file into R, convert it to a tsibble, create plots of the three variables, and compare the graph with and without facet_grid().

Place tute1.csv in the same folder as your Quarto file before running this code.

tute1 <- read.csv("tute1.csv")
mytimeseries <- tute1 |>
  mutate(Quarter = yearquarter(Quarter)) |>
  as_tsibble(index = Quarter)
mytimeseries |>
  pivot_longer(-Quarter) |>
  ggplot(aes(x = Quarter, y = value, color = name)) +
  geom_line() +
  facet_grid(name ~ ., scales = "free_y")

mytimeseries |>
  pivot_longer(-Quarter) |>
  ggplot(aes(x = Quarter, y = value, color = name)) +
  geom_line()

The first graph separates Sales, AdBudget, and GDP into their own panels. This makes each variable easier to see because they have different ranges of values.

When facet_grid() is removed, all three variables appear on the same graph. This makes comparison possible, but some of the patterns are harder to see because the variables use different scales.

Exercise 2.4

Use the USgas package to examine natural gas consumption in the United States. Convert us_total into a tsibble using year as the index and state as the key. Then plot annual natural gas consumption for the six New England states.

install.packages("USgas")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.6'
## (as 'lib' is unspecified)
library(USgas)

gas <- us_total |>
  as_tsibble(index = year, key = state)
gas |>
  filter(state %in% c(
    "Maine",
    "Vermont",
    "New Hampshire",
    "Massachusetts",
    "Connecticut",
    "Rhode Island"
  )) |>
  autoplot(y) +
  labs(
    title = "Natural Gas Consumption in New England",
    x = "Year",
    y = "Natural Gas Consumption"
  )

The graph compares annual natural gas consumption for the six New England states.

Natural gas use changes over time and differs by state. The larger states generally use more natural gas than the smaller states. The graph also shows that consumption does not remain constant from year to year.

Exercise 2.5

Download tourism.xlsx and read it into R. Convert it into a tsibble matching the tourism dataset, determine which Region and Purpose combination has the highest average number of overnight trips, and create a new tsibble containing total trips by State.

Place tourism.xlsx in the same folder as your Quarto file.

install.packages("readxl")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.6'
## (as 'lib' is unspecified)
library(readxl)

tourism_data <- read_excel("tourism.xlsx")
tourism_ts <- tourism_data |>
  mutate(Quarter = yearquarter(Quarter)) |>
  as_tsibble(
    index = Quarter,
    key = c(Region, State, Purpose)
  )
tourism_ts |>
  as_tibble() |>
  group_by(Region, Purpose) |>
  summarise(Average_Trips = mean(Trips)) |>
  arrange(desc(Average_Trips))
## `summarise()` has regrouped the output.
## ℹ Summaries were computed grouped by Region and Purpose.
## ℹ Output is grouped by Region.
## ℹ Use `summarise(.groups = "drop_last")` to silence this message.
## ℹ Use `summarise(.by = c(Region, Purpose))` for per-operation grouping
##   (`?dplyr::dplyr_by`) instead.
state_trips <- tourism_ts |>
  group_by(State) |>
  summarise(Trips = sum(Trips))

state_trips

The Region and Purpose combination with the highest average number of overnight trips is Sydney for Visiting, with an average of approximately 747 trips.

The second part combines the different Regions and Purposes and calculates total trips for each State during each quarter. This makes it easier to examine tourism at the state level instead of separating the data by individual regions and purposes.

Exercise 2.8

Use autoplot(), gg_season(), gg_subseries(), gg_lag(), and ACF() to explore these five time series:

Total Private employment from us_employment Bricks from aus_production Hare from pelt H02 Cost from PBS Barrels from us_gasoline

Discuss whether each series has trend, seasonality, or cycles, describe the seasonal patterns, and identify any unusual years.

Total Private Employment

employment <- us_employment |>
  filter(Title == "Total Private")
employment |>
  autoplot(Employed)

employment |>
  gg_season(Employed)

employment |>
  gg_subseries(Employed)

employment |>
  gg_lag(Employed)

employment |>
  ACF(Employed) |>
  autoplot()

Total private employment has a strong long-term upward trend. There are also periods where employment rises and falls because of economic cycles.

The seasonal pattern is relatively small compared with the overall trend. Some unusual drops can be seen during major economic downturns, such as around 2008.

Bricks

bricks <- aus_production |>
  select(Quarter, Bricks)
bricks |>
  autoplot(Bricks)
## Warning: Removed 20 rows containing missing values or values outside the scale range
## (`geom_line()`).

bricks |>
  gg_season(Bricks)
## Warning: Removed 20 rows containing missing values or values outside the scale range
## (`geom_line()`).

bricks |>
  gg_subseries(Bricks)
## Warning: Removed 20 rows containing missing values or values outside the scale range
## (`geom_line()`).

bricks |>
  gg_lag(Bricks)
## Warning: Removed 20 rows containing missing values (gg_lag).

bricks |>
  ACF(Bricks) |>
  autoplot()

Brick production increased for many years before becoming more stable and eventually decreasing.

There is a clear quarterly seasonal pattern. Production tends to be higher during some quarters than others. There are also longer periods of increases and decreases in production. A noticeable decrease occurs around the early 1990s.

Hare

hare <- pelt |>
  select(Year, Hare)
hare |>
  autoplot(Hare)

hare |>
  gg_lag(Hare)

hare |>
  ACF(Hare) |>
  autoplot()

The Hare data does not show seasonality because the observations are annual.

However, there is a strong repeating cycle where the number of hare pelts increases and decreases over several years. There is not a clear long-term upward or downward trend.

H02 Prescription Cost

h02 <- PBS |>
  filter(ATC2 == "H02") |>
  summarise(Cost = sum(Cost))
h02 |>
  autoplot(Cost)

h02 |>
  gg_season(Cost)

h02 |>
  gg_subseries(Cost)

h02 |>
  gg_lag(Cost)

h02 |>
  ACF(Cost) |>
  autoplot()

The H02 prescription cost data has an upward trend and a strong seasonal pattern.

Costs change depending on the month of the year, and similar patterns repeat each year. The ACF also shows strong correlation between observations that occur at similar times in different years.

Gasoline

gasoline <- us_gasoline
gasoline |>
  autoplot(Barrels)

gasoline |>
  gg_season(Barrels)

gasoline |>
  gg_subseries(Barrels)

gasoline |>
  gg_lag(Barrels)

gasoline |>
  ACF(Barrels) |>
  autoplot()

Gasoline consumption generally increases over the earlier part of the series, although there are periods where this trend changes.

The series also contains shorter-term fluctuations and some cyclical behavior. There are noticeable changes around the late 2000s where the previous upward trend becomes weaker.

The five time series show different types of time-series behavior. Total private employment has a strong upward trend with economic cycles. Brick production has both trend and seasonality. Hare pelts show strong cycles but no seasonal pattern because the data is annual. H02 prescription costs have both an upward trend and strong seasonality. Gasoline consumption has a longer-term trend along with shorter-term fluctuations.

These graphs demonstrate why it is important to examine a time series visually before selecting a forecasting model. Different datasets can contain trend, seasonality, cycles, or combinations of these patterns.