Table of Contents
To convert a data frame to a time series in R, the data frame needs to contain a date or datetime column that will be used as the time index. Once the data frame is loaded, the xts package can be used to convert it to a time series object by using the as.xts() function. The first argument should be the data frame, followed by the order.by argument, which should specify the date or datetime column. The column will also be used as the index for the time series object.
The easiest way to convert a data frame to a time series object in R is to use the read.zoo() function from the zoo package:
tseries <- read.zoo(df)
The following example shows how to use this function in practice.
Example: Convert Data Frame to Time Series in R
Suppose we have the following data frame in R:
#create data frame df <- data.frame(date = as.Date('2022-01-01') + 0:9, sales = runif(10, 10, 500) + seq(50, 59)^2) #view data frame df date sales 1 2022-01-01 2797.159 2 2022-01-02 2782.148 3 2022-01-03 2801.773 4 2022-01-04 3257.546 5 2022-01-05 3415.920 6 2022-01-06 3267.564 7 2022-01-07 3577.496 8 2022-01-08 3627.193 9 2022-01-09 3509.547 10 2022-01-10 3670.815
We can use the class() function to confirm that df is currently a data frame:
#display class of df
class(df)
[1] "data.frame"
To convert the data frame to a time series object, we can use the read.zoo() function from the zoo package:
library(zoo) #convert data frame to time series tseries <- read.zoo(df) #view time series tseries 2022-01-01 2022-01-02 2022-01-03 2022-01-04 2022-01-05 2022-01-06 2022-01-07 2797.159 2782.148 2801.773 3257.546 3415.920 3267.564 3577.496 2022-01-08 2022-01-09 2022-01-10 3627.193 3509.547 3670.815
And we can use the class() function to confirm that tseries has a “zoo” time series class.
#display class of tseries
class(tseries)
[1] "zoo"
We can use also use the as.ts() function to convert the “zoo” time series object to a “ts” time series object:
#convert to ts object tseries_ts <- as.ts(tseries) #view time series object tseries_ts Time Series: Start = 18993 End = 19002 Frequency = 1 [1] 2797.159 2782.148 2801.773 3257.546 3415.920 3267.564 3577.496 3627.193 [9] 3509.547 3670.815 #view class class(tseries_ts) [1] "ts"
Depending on your end goal, it might make more sense to convert the data frame to a “zoo” time series object or a “ts” time series object.
The following tutorials explain how to perform other common tasks in R: