Chapter 3 Handling Time Series in R
3.1 The xts class
The xts class is one class for handling time series data. Internally, xts objects are matrix objects indexed by a formal time object. This time object can be and in this section we discuss basic manipulations for xts objects.
3.1.1 Creating xts objects
The function xts is the constructor function for xts objects and it takes a number of arguments. The 2 most important ones are x and order.by with x being a vector or matrix containing the data and order.by containing the corresponding vector of time or dates - the length of the vector order.by must be of the same length as x. The following example creates a short sample of random data and corresponding dates.
# Create a vector of length 10
data <- rnorm(10)
# Create dates
dates <- seq(as.Date("2020-01-01"),length=10,by = "days")
# create the xts-object test using xts()
test <- xts(x=data, order.by=dates)
Sometimes we do have the opposite problem, i.e. we have an xts-object but for further manipulation we want to extract the data and/or the time index. To extract the data from an xts-object we use the function ‘coredata()’:
## [,1]
## [1,] -0.63189623
## [2,] 0.42631952
## [3,] -0.71221789
## [4,] 0.96177386
## [5,] 0.23834026
## [6,] 1.60642775
## [7,] -0.05105104
## [8,] 1.33601145
## [9,] -1.51839633
## [10,] -0.49369998
To extract the time index we use the function ‘index()’
## [1] "2020-01-01" "2020-01-02" "2020-01-03" "2020-01-04" "2020-01-05"
## [6] "2020-01-06" "2020-01-07" "2020-01-08" "2020-01-09" "2020-01-10"