Time series objects with the zoo package

Manipolare dati di serie temporali in R

Harrison Brown

Graduate Researcher in Geography

The zoo package

zoo

  • Provides zoo class of objects
  • Functions for manipulating and visualizing time series data
Manipolare dati di serie temporali in R

zoo versus base R

base R:

  • stats::ts class
  • Only regularly-spaced intervals
  • Can be tedious to create data frames

zoo:

  • zoo class
  • Regular or irregular intervals
  • Methods for converting to data frame
Manipolare dati di serie temporali in R

Creating a zoo object

sample_values
[1] 4.224 5.495 6.156
[4] 6.397 6.291 6.262
...
sample_dates
[1] "2022-01-20" "2022-01-21"
[3] "2022-01-22" "2022-01-23"
[5] "2022-01-24" "2022-01-25"
...
Manipolare dati di serie temporali in R

Creating a zoo object

library(zoo)
my_zoo <- zoo(x = sample_values,
              order.by = sample_dates)
my_zoo
2022-01-20 4.224
2022-01-21 5.495
2022-01-22 6.156
2022-01-23 6.397
2022-01-24 6.291
2022-01-25 6.262
...
Manipolare dati di serie temporali in R

Converting to zoo from ts

class(AirPassengers)
[1] "ts"
AP_zoo <- zoo::as.zoo(AirPassengers)
class(AP_zoo)
[1] "zoo"
Manipolare dati di serie temporali in R

zoo versus ts

print(AirPassengers)
     Jan Feb Mar Apr May Jun Jul ...
1949 112 118 132 129 121 135 148 ...
1950 115 126 141 135 125 149 170 ...
1951 145 150 178 163 172 178 199 ...
1952 171 180 193 181 183 218 230 ...
1953 196 196 236 235 229 243 264 ...
...
print(AP_zoo)
Jan 1949 112
Feb 1949 118
Mar 1949 132
Apr 1949 129
May 1949 121
Jun 1949 135
Jul 1949 148
Aug 1949 148
Sep 1949 136
...
Manipolare dati di serie temporali in R

zoo and ggplot2

library(ggplot2)

ggplot(data = my_zoo,
       aes(x = Index, y = my_zoo)) +

geom_line(color = "blue", size = 2, linetype = "dotted") +
scale_y_continuous() +
theme_bw() + labs(x = "Index", y = "Value", title = "Plotting a zoo Object")
Manipolare dati di serie temporali in R

zoo and ggplot2

Plot of the 'my_zoo' time series. This plot highlights how the user can incorporate different plotting elements from the ggplot2 package, using syntax similar to plotting a data frame, such as axis labels, a title, plotting themes, color, and so on.

Manipolare dati di serie temporali in R

Let's practice!

Manipolare dati di serie temporali in R

Preparing Video For Download...