Search code examples
rdataframextsposixct

xts function doesn't consider my POSIXct dates as an appropriate time-based object


I have created a dataframe with two columns.

> head(data_frame)
                 Date Rainfall
1 1992-01-06 14:00:00      0.3
2 1992-01-06 15:00:00      0.2
3 1992-01-06 16:00:00      0.3
4 1992-01-06 18:00:00      0.1
5 1992-01-06 19:00:00      0.3
6 1992-01-06 20:00:00      0.8

Rainfall is numeric and Date is POSIXct.

> class(data_frame$Date)
[1] "POSIXct"
> class(data_frame$Rainfall)
[1] "numeric"

When I try to create a time series using xts function, I get the following error:

> time_series   <- xts::xts(data_frame$Rainfall, order.by = data_frame$Date)
Error in xts::xts(data_frame$Rainfall, order.by = data_frame$Date) : 
  order.by requires an appropriate time-based object

xts should be able to handle POSIXct. I went through a similar question posted here, where the solution was to convert date into the above format. Looking at those answers, my code should work. I can't figure out why it is not.

Reproducible example:

head_data_frame = structure(list(
  Date = structure(
    c(
      694659600,
      694663200,
      694666800,
      694674000,
      694677600,
      694681200
    ),
    class = "POSIXct"
  ),
  Rainfall = c(0.3,
               0.2, 0.3, 0.1, 0.3, 0.8)
),
row.names = c(NA, 6L),
class = "data.frame")

Solution

  • The class appears to be broken, did you use a package? Normally it's c("POSIXct", "POSIXt") but yours is just "POSIXt".

    class(head_data_frame$Date)
    # [1] "POSIXct"
    

    Fix:

    class(head_data_frame$Date) <- c("POSIXct", "POSIXt")
    

    Test:

    xts::xts(head_data_frame$Rainfall, order.by = head_data_frame$Date)
    #                     [,1]
    # 1992-01-06 02:00:00  0.3
    # 1992-01-06 03:00:00  0.2
    # 1992-01-06 04:00:00  0.3
    # 1992-01-06 06:00:00  0.1
    # 1992-01-06 07:00:00  0.3
    # 1992-01-06 08:00:00  0.8
    

    Works! :)