Introduction
zoo and xts provide classes for time series data. They are the foundation for time series analysis in R.
Creating zoo/xts
library(xts)
# From vector
z <- zoo(x, order.by = dates)
# From data frame
x <- as.xts(df)
# Create with time
x <- xts(x, order.by = as.POSIXct(dates))
Time Series Operations
# Subset by time
x["2020"]
x["2020-01"]
x["2020-01-01/2020-01-31"]
# Lag/lead
lag(x, k = 1)
diff(x)
# Rolling functions
rollapply(x, 10, mean)
Merging
# Merge series
merge(x, y, all = FALSE)
# Fill NA
na.locf(x)
na.approx(x)
Conversion
# To dataframe
as.data.frame(x)
# To matrix
as.matrix(x)
# To zoo
as.zoo(x)
Summary
zoo/xts provide efficient time series operations. Use them for financial and temporal data.