如何正确制作xts对象

时间:2015-06-30 21:45:14

标签: r xts

我有时间和价格的数据,我想制作一个xts对象。因此,我写道:

head(all)
class(all$Time)
class(all$Price)
all$Time<- as.POSIXct(all$Time) # convert time to a factor
class(all$Time)
xt<- as.xts(all, order.by= as.POSIXct(as.character(all$Time) ))
class(xt$Time)
class(xt$Price)
head(xt)

输出

> head(all)

                           Time  Price
1 2015/06/29 09:30:00.127000000 163.98
2 2015/06/29 09:30:00.173000000 163.92
3 2015/06/29 09:30:00.173000000 163.98
4 2015/06/29 09:30:00.173000000 163.98
5 2015/06/29 09:30:00.173000000 163.98
6 2015/06/29 09:30:00.173000000 163.99
> class(all$Time)
[1] "factor"
> class(all$Price)
[1] "numeric"
> all$Time<- as.POSIXct(all$Time)
> class(all$Time)
[1] "POSIXct" "POSIXt" 
> xt<- as.xts(all, order.by= as.POSIXct(as.character(all$Time) ))
> class(xt$Time)
[1] "xts" "zoo"
> class(xt$Price)
[1] "xts" "zoo"
> head(xt)
                    Time                  Price     
2015-06-29 09:30:00 "2015-06-29 09:30:00" "163.9800"
2015-06-29 09:30:00 "2015-06-29 09:30:00" "163.9200"
2015-06-29 09:30:00 "2015-06-29 09:30:00" "163.9800"
2015-06-29 09:30:00 "2015-06-29 09:30:00" "163.9800"
2015-06-29 09:30:00 "2015-06-29 09:30:00" "163.9800"
2015-06-29 09:30:00 "2015-06-29 09:30:00" "163.9900"

正如您所看到的,xts对象看起来像一个角色。我怎样才能正确地制作它以便它只是时间和价格?

1 个答案:

答案 0 :(得分:1)

由于您的数据有毫秒信息,您可以尝试:

options(digits.secs=6)
all$Time <- strptime(all$Time, format ="%Y/%m/%d %H:%M:%OS")
xts_price<-xts(all$Price,all$Time)
colnames(xts_price) <- "Price"
#> xts_price
#                         Price
#2015-06-29 09:30:00.127 163.98
#2015-06-29 09:30:00.173 163.92
#2015-06-29 09:30:00.173 163.98
#2015-06-29 09:30:00.173 163.98
#2015-06-29 09:30:00.173 163.98
#2015-06-29 09:30:00.173 163.99
#> class(xts_price)
#[1] "xts" "zoo"

希望这有帮助。