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

Posted

技术标签:

【中文标题】xts 函数不将我的 POSIXct 日期视为适当的基于时间的对象【英文标题】:xts function doesn't consider my POSIXct dates as an appropriate time-based object 【发布时间】:2021-11-20 09:54:10 【问题描述】:

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

> 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 是数字,Date 是 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。我遇到了here 发布的类似问题,解决方案是将日期转换为上述格式。看看这些答案,我的代码应该可以工作。我不知道为什么不是。

可重现的例子:

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

【问题讨论】:

【参考方案1】:

该类似乎已损坏,您是否使用了包?通常是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

有效! :)

【讨论】:

【参考方案2】:

如果我将时区更改为 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 (). 

【讨论】:

确实有效,谢谢! 这也可以在没有额外软件包的情况下完成,例如:head_data_frame |&gt; read.zoo(tz = "") |&gt; as.xts() 或指定不同的时区。

以上是关于xts 函数不将我的 POSIXct 日期视为适当的基于时间的对象的主要内容,如果未能解决你的问题,请参考以下文章

read.xlsx 函数正在将我的变量之一读取为“因子”而不是“POSIXct”

xts 时间序列中日期之前的 X

为什么cut()将我的POSIXct向量转换为因子向量,我该怎么做才能阻止它?

为啥标准不将模板构造函数视为复制构造函数?

为啥我的数字变量有日期以及如何将整个内容转换为 xts?

过滤某些月份的 POSIXct 日期时间