Search code examples
rtime-seriesforecasting

Convert a data frame with Product_Type, Date and Demand to timeseries object?


Product_Code    Date    Order_Demand
Product_1904    09-01-2017  4000
Product_0250    09-01-2017  148
Product_0471    09-01-2017  30
Product_1408    06-01-2017  1000
Product_0689    06-01-2017  200
Product_0689    06-01-2017  300
Product_1926    06-01-2017  2
Product_1938    06-01-2017  20

I am new to R. I want to convert the above data to a time series object ts, such that the rownames will be Product_Code and column names will be months or quarters. Kindly help me!!


Solution

  • I think this should work for you,

    library(xts)
    library(lubridate)
    
    # dummmy data
    test_data <- data.frame(
      Product_Code = c("Product_1904","Product_0250","Product_0471"),
      Date = mdy(c("09-01-2017","09-02-2017","09-03-2017")),
      Order_Demand = c(4000,148,30)
    )
    
    # convert dummy data into xts time series
    xts::xts(test_data, order.by = test_data$Date) -> time_series_data
    
    str(time_series_data)
    
    An ‘xts’ object on 2017-09-01/2017-09-03 containing:
      Data: chr [1:3, 1:3] "Product_1904" "Product_0250" "Product_0471" "2017-09-01" "2017-09-02" "2017-09-03" "4000" ...
     - attr(*, "dimnames")=List of 2
      ..$ : NULL
      ..$ : chr [1:3] "Product_Code" "Date" "Order_Demand"
      Indexed by objects of class: [Date] TZ: UTC
      xts Attributes:  
     NULL
    

    From next time please use dput() and copy paste the result from the R terminal to provide the data.