首页 > 解决方案 > 将不规则间隔数据转换为时间序列

问题描述

我有一段时间内的销售数据,我想将数据转换为时间序列以进行时间序列相关分析。但我被困在第一步,请建议如何进行。下面是我的交易数据,order_date、total_amount 和 Quantity。我的订单日期是随机的(不均匀分布)。

> sku_top_02
         ord_date total_amount qty
36015  2014-01-02       379.81   1
36022  2014-01-02       610.87   2
36050  2014-01-03       289.17   6
36081  2014-01-03       183.12   1
36128  2014-01-06       303.57  10
36193  2014-01-06        51.65   1
36259  2014-01-07       250.31   1
36222  2014-01-08       408.58   1
36264  2014-01-09       183.40   1
36347  2014-01-09       504.90   1
36323  2014-01-13       529.95   1
36412  2014-01-13       204.96   1
36455  2014-01-14       524.83   5
36504  2014-01-14      3771.41  25
36762  2014-01-20       759.86   2
36794  2014-01-21       539.88   2
36826  2014-01-22       599.34   1
37056  2014-01-22       133.35   3
37076  2014-01-22       174.25   4
...
...
...
Please ignore the first column (rownames, after sorting by order date it is jumbled). Below, I am using xts() to convert the data into time-series.

> ts.sku_02 <- xts(df = sku_top_02[,c('total_amount', 'qty')], order.by = sku_top_02$ord_date)

我的转换中有些东西不起作用

> ts.sku_02
Data:
numeric(0)

Index:
 Date[1:4386], format: "2014-01-02" "2014-01-02" "2014-01-03" "2014-01-03" "2014-01-06" "2014-01-06" "2014-01-07" "2014-01-08" "2014-01-09" "2014-01-09" ...
> dim(ts.sku_02)
NULL
> str(ts.sku_02)
An 'xts' object of zero-width

另外,我无法绘制 TS。请建议如何进行。提前致谢。

标签: rdataframexts

解决方案


假设在最后的注释中可重现地显示输入数据框:

library(xts)
x <- xts(DF[-1], DF[[1]])

给予:

> head(x)
           total_amount qty
2014-01-02       379.81   1
2014-01-02       610.87   2
2014-01-03       289.17   6
2014-01-03       183.12   1
2014-01-06       303.57  10
2014-01-06        51.65   1

笔记

Lines <- "ord_date total_amount qty
36015  2014-01-02       379.81   1
36022  2014-01-02       610.87   2
36050  2014-01-03       289.17   6
36081  2014-01-03       183.12   1
36128  2014-01-06       303.57  10
36193  2014-01-06        51.65   1
36259  2014-01-07       250.31   1
36222  2014-01-08       408.58   1
36264  2014-01-09       183.40   1
36347  2014-01-09       504.90   1
36323  2014-01-13       529.95   1
36412  2014-01-13       204.96   1
36455  2014-01-14       524.83   5
36504  2014-01-14      3771.41  25
36762  2014-01-20       759.86   2
36794  2014-01-21       539.88   2
36826  2014-01-22       599.34   1
37056  2014-01-22       133.35   3
37076  2014-01-22       174.25   4"
DF <- read.table(text = Lines)
DF$ord_date <- as.Date(DF$ord_date)

推荐阅读