R How to Convert Data Frame to xts & zoo Time Series (Example Code)

In this tutorial, I’ll illustrate how to change the data frame class to the xts / zoo data type in the R programming language.

Preparing the Example

my_df <- data.frame(my_dates = c("2010-01-11",    # Data frame for example
                                 "2023-12-18",
                                 "2017-04-28",
                                 "2020-07-25",
                                 "2028-10-16",
                                 "2020-10-12",
                                 "2015-04-03"),
                    my_values = 10:16)
my_df                                             # Show example data frame in console
#     my_dates my_values
# 1 2010-01-11        10
# 2 2023-12-18        11
# 3 2017-04-28        12
# 4 2020-07-25        13
# 5 2028-10-16        14
# 6 2020-10-12        15
# 7 2015-04-03        16
install.packages("xts")                             # Install & load xts
library("xts")

Example: Change Data Frame Class to Time Series Object

my_df$my_dates <- as.Date(my_df$my_dates)         # Converting date column to Date class
my_ts <- xts(my_df$my_values, my_df$my_dates)     # Converting data frame to xts
my_ts                                             # Show time series in console
#            [,1]
# 2010-01-11   10
# 2015-04-03   16
# 2017-04-28   12
# 2020-07-25   13
# 2020-10-12   15
# 2023-12-18   11
# 2028-10-16   14

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top