Time series is one of the most common analysis and modeling in Data Science. In this article, we will learn how to create time series in R.
Let’s say we had a vector of sales data. In this example, we have five elements with dollars values, i.e. 400, etc.
sales <- c(300, 400, 100, 400, 800)Now, let’s say we want to convert this to a time series object which
will index our data by date. We can use the built in ts method. We
will use three parameters: data, which will take our sales data above,
start, which will set to start In January of 2018, and frequency, which
will set to 1 to represent once a year.
sales.data <- ts(data = sales, start = c(2018, 1), frequency = 1)
sales.data## Time Series:
## Start = 2018
## End = 2022
## Frequency = 1
## [1] 300 400 100 400 800Here you can see that we now have a Time Series object that spans from 2018 to 2022.
If our data was not yearly, we can change the frequency. Let’s assume the sales were quartly. We can change the frequency to 4.
sales.data <- ts(data = sales, start = c(2018, 1), frequency = 5)
sales.data## Time Series:
## Start = c(2018, 1)
## End = c(2018, 5)
## Frequency = 5
## [1] 300 400 100 400 800Now our data represents sales per a quarter.
The built in ts function is great, but there are alternatives that you
may see while using time series data.
Let’s start with the zoo library, which adds a lot of functionality to
the build in time series. We can create an object using the zoo
function.
library(zoo)## Warning: package 'zoo' was built under R version 4.0.5
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numericzoo(sales.data)## 2018 2018.2 2018.4 2018.6 2018.8
## 300 400 100 400 800If we didn’t have a time series object already, we can pass our sales data and a sequence of dates to zoo.
days <- seq(as.Date("2018-01-01"), as.Date("2018-01-05"), by = "days")
zoo(sales, days)## 2018-01-01 2018-01-02 2018-01-03 2018-01-04 2018-01-05
## 300 400 100 400 800Another library you may see is the xts library. It extends zoo, so
anything that works with zoo also works with xts. We can create an
xts time series the same way as zoo.
library(xts)## Warning: package 'xts' was built under R version 4.0.5days <- seq(as.Date("2018-01-01"), as.Date("2018-01-05"), by = "days")
xts(sales, days)## [,1]
## 2018-01-01 300
## 2018-01-02 400
## 2018-01-03 100
## 2018-01-04 400
## 2018-01-05 800