Open In App

Convert DataFrame with Date Column to Time Series Object in R

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to convert dataframe with date column to time series object in the R programming language.

Time series object are a series of data points in which each data point is associated with a timestamp. For example, is a price of a stock in the stock market at different points of time. The data for the time series is stored in an R object called time-series object. These are also called as xts / zoo Object.

To convert the given dataframe with the date column to the time series object, the user first needs to import and load the xts package.

Syntax:

install.packages(“xts”)                   

library(“xts”)

The user then needs to call the xts() function with the required parameters the main need to call this function is to create the time-series object in R language and at the end use is.xts() function we will be conforming to the time-series object created by xts() function in R language.

 xts() function is basically used as the constructor for creating an extensible time-series object.

Syntax:

xts(x = NULL, order.by = index(x), frequency = NULL,  unique = TRUE, tzone = Sys.getenv(“TZ”),  …)

Parameters:

  • x:-an object containing the time series data
  • order.by:-a corresponding vector of unique times/dates – must be of a known time-based class.
  • frequency:-numeric indicating the frequency of order.
  • unique:-should index be checked for unique time-stamps?
  • tzone:-time zone of series. This is ignored for Date indices
  • …:-additional attributes to be added.

Example:

R




library("xts")
  
gfg_date <- data.frame(date = c("2004-05-07","2005-10-12",
                                "2011-11-11","2020-11-11",
                                "2021-12-11"),val=c(1,2,3,4,5))
  
gfg_date$date<-as.Date(gfg_date$date)  
  
gfg_ts <- xts(gfg_date$val, gfg_date$date)
gfg_ts    
  
is.xts(gfg_ts)


Output:


Last Updated : 23 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads