我创建了一个包含两列的数据框。
> 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。我经历过类似的问题here https://stackoverflow.com/questions/64447398/xts-does-not-recognize-datetime-as-an-appropriate-time-based-object,解决方案是将日期转换为上述格式。看看这些答案,我的代码应该可以工作。我不明白为什么不是。
可重现的例子:
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")