将数据帧转换为R中的单变量时间序列?
问题描述:
我想将此数据帧转换为R中的单变量时间序列。为此,我想我想将date_time
列变为索引?让我知道这听起来是否正确。下面是实际的数据帧的一小部分:将数据帧转换为R中的单变量时间序列?
date_time price
2017-05-01 00:00:00 3040
2017-05-01 01:00:00 3030
2017-05-01 02:00:00 3068
2017-05-01 03:00:00 3010
2017-05-01 04:00:00 2814
这是我试图做到这一点。
xts(df$price, as.Date(df$date_time, format='%Y-%m-%d %H:%M:%S'))
但是,这完全切断了小时,分钟和秒钟。因此它会输出:
price
2017-05-01 3040
2017-05-01 3030
2017-05-01 3068
2017-05-01 3010
2017-05-01 2814
如何在索引中包含日期和时间?
答
假设ss
是数据帧的名称,下面的代码应该工作:
library(xts)
time <- as.POSIXct(ss$date_time, format = '%Y-%m-%d %H:%M:%S')
#library(xts)
xt <- xts(x = ss$price, order.by = time)
xt1 <- xts(ss$price, strptime(ss$date_time, format = '%Y-%m-%d %H:%M:%S'))
xt1
> xt1
[,1]
2017-05-01 00:00:00 3040
2017-05-01 01:00:00 3030
2017-05-01 02:00:00 3068
2017-05-01 03:00:00 3010
2017-05-01 04:00:00 2814
as.Date()
将因此失去time
元件它必须被类型强制转换到一个POSIXct
对象。
可以请你把你的数据 –
作为@amrrs指出的,这是一个数据类型的问题,你需要处理日期和时间。 “chron”图书馆是另一种选择。 – Marco