Convert Data Frame with Date Column to Time Series Object in R (Example)
In this article you’ll learn how to change the data frame class to the xts / zoo data type in the R programming language.
Table of contents:
Let’s take a look at some R codes in action!
Creation of Example Data
We use the following data as basement for this R tutorial:
data <- data.frame(date = c("2020-10-01", # Create example data "2021-07-08", "2018-01-18", "2018-05-05", "2025-12-10"), value = 1:5) data # Print example data # date value # 1 2020-10-01 1 # 2 2021-07-08 2 # 3 2018-01-18 3 # 4 2018-05-05 4 # 5 2025-12-10 5
Have a look at the previous output of the RStudio console. It shows that our example data has two columns. The first variable contains dates formatted as character strings and the second variable contains some randomly selected values.
We can also check the class of our data:
class(data) # Check class of data # "data.frame"
As you can see, our example data has the data.frame class.
Example: Converting Data Frame to xts / zoo Object
This Example illustrates how to switch from data.frame class to a time series object (i.e. xts or zoo). First, we have to convert our character string variable to the Date class.
data$date <- as.Date(data$date) # Convert character string column to date
We also need to install and load the xts package:
install.packages("xts") # Install & load xts package library("xts")
We can use the xts function provided by the xts package to convert our data frame to a time series object as shown below:
data_ts <- xts(data$value, data$date) # Convert data frame to time series data_ts # Print time series # [,1] # 2018-01-18 3 # 2018-05-05 4 # 2020-10-01 1 # 2021-07-08 2 # 2025-12-10 5
Let’s check the data type of our updated data object:
class(data_ts) # Check class of time series # "xts" "zoo"
As you can see, we switched the class from data.frame to xts / zoo.
Video, Further Resources & Summary
In case you need further explanations on the R programming code of the present tutorial, you could have a look at the following video of my YouTube channel. In the video, I show the content of this article in a live session.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you might want to have a look at the related posts of this website. I have released several articles already:
- Merge Time Series in R
- lead & lag R Functions of dplyr Package
- Draw Time Series Plot with Events Using ggplot2 Package
- as.Date Function in R
- The R Programming Language
In summary: In this tutorial you learned how to convert data frames to times series objects in the R programming language. In case you have additional questions, please tell me about it in the comments section.