xts 函数不将我的 POSIXct 日期视为适当的基于时间的对象

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

我创建了一个包含两列的数据框。

> 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

降雨量是数字,日期是 POSIXct。

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

当我尝试使用 xts 函数创建时间序列时,出现以下错误:

> 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 应该能够处理 POSIXct。我经历了一个类似的问题 ,解决方案是将日期转换为上述格式。查看这些答案,我的代码应该可以工作。我不明白为什么不是。

可重现的例子:

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")

如果我将时区更改为 UTC,我可以让它工作。

head_data_frame$Date <- lubridate::force_tz(head_data_frame$Date, tzone = "UTC")
xts::xts(head_data_frame$Rainfall, order.by = head_data_frame$Date)

#                    [,1]
#1992-01-06 09:00:00  0.3
#1992-01-06 10:00:00  0.2
#1992-01-06 11:00:00  0.3
#1992-01-06 13:00:00  0.1
#1992-01-06 14:00:00  0.3
#1992-01-06 15:00:00  0.8
#Warning message:
#timezone of object (UTC) is different than current timezone (). 

class好像坏了,你用的是包吗?通常它是 c("POSIXct", "POSIXt") 但你的只是 "POSIXt".

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

修复:

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

测试:

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

有效! :)