## date price
## <date> <int>
## 1 2010-01-01 6558
## 2 2010-02-01 7481
## 3 2010-03-01 9475
## 4 2010-04-01 9424
## 5 2010-05-01 9351
## 6 2010-06-01 10552
## 7 2010-07-01 9077
## 8 2010-08-01 9273
## 9 2010-09-01 9420
## 10 2010-10-01 9413
## # ... with 74 more rows
tk_ts
有许多包用了另一种类型的时间序列数据——ts
,其中最常见的可能就是 forecast
包。使用 tk_ts()
函数的优点有两个:
- 与其他
tk_
函数兼容,可以方便直接的实现数据的转换和逆转换。
- 更重要的是:当使用
tk_ts
函数时,ts
对象将初始的不规则时间索引(通常是具体的日期)转换成一个索引属性。这使得保留日期和时间信息成为可能。
一个例子,使用 tk_tbl(timetk_index = TRUE)
函数转换成 ts
对象。因为 ts
对象只能处理规则时间索引,我们需要添加参数 start = 2010
和 freq = 12
。
# Coerce to ts
beer_sales_ts <- tk_ts(
beer_sales_tbl,
start = 2010,
freq = 12)
# Show the calendar-printout
beer_sales_ts
## Jan Feb Mar Apr May Jun Jul Aug Sep Oct
## 2010 6558 7481 9475 9424 9351 10552 9077 9273 9420 9413
## 2011 6901 8014 9833 9281 9967 11344 9106 10468 10085 9612
## 2012 7486 8641 9709 9423 11342 11274 9845 11163 9532 10754
## 2013 8395 8888 10109 10493 12217 11385 11186 11462 10494 11541
## 2014 8559 9061 10058 10979 11794 11906 10966 10981 10827 11815
## 2015 8398 9061 10720 11105 11505 12903 11866 11223 12023 11986
## 2016 8540 10158 11879 11155 11916 13291 10540 12212 11786 11424
## Nov Dec
## 2010 9866 11455
## 2011 10328 11483
## 2012 10953 11922
## 2013 11139 12709
## 2014 10466 13303
## 2015 11510 14190
## 2016 12482 13832
有两种方法转换回 tbl
:
- 直接使用
tk_tbl()
,我们将得到 YEARMON
类型的“规则”的时间索引(来自 zoo
包)。
- 如果原始对象用
tk_ts()
创建,并且有属性 timetk_index
,我们可以通过命令 tk_tbl(timetk_index = TRUE)
转换回去,并得到 Date
格式 “非规则”时间索引。
方法 1:注意,日期列是 YEARMON
类型的。
tk_tbl(beer_sales_ts, rename_index = "date")
## # A tibble: 84 x 2
## date price
## <S3: yearmon> <int>
## 1 Jan 2010 6558
## 2 Feb 2010 7481
## 3 Mar 2010 9475
## 4 Apr 2010 9424
## 5 May 2010 9351
## 6 Jun 2010 10552
## 7 Jul 2010 9077
## 8 Aug 2010 9273
## 9 Sep 2010 9420
## 10 Oct 2010 9413
## # ... with 74 more rows
方法 2:设置参数 timetk_idx = TRUE
来找回初始的日期或时间信息。
首先,用 has_timetk_idx()
检查 ts
对象是否存在 timetk
索引。
# Check for timetk index.
has_timetk_idx(beer_sales_ts)
## [1] TRUE
如果返回值是 TRUE
,在调用 tk_tbl()
时设定 timetk_idx = TRUE
。现在可以看到日期列是 date
类型的,这在以往不容易做到。
# If timetk_idx is present, can get original dates back
tk_tbl(beer_sales_ts, timetk_idx = TRUE, rename_index = "date")
## # A tibble: 84 x 2
## date price
## <date> <int>
## 1 2010-01-01 6558
## 2 2010-02-01 7481
## 3 2010-03-01 9475
## 4 2010-04-01 9424
## 5 2010-05-01 9351
## 6 2010-06-01 10552
## 7 2010-07-01 9077
## 8 2010-08-01 9273
## 9 2010-09-01 9420
## 10 2010-10-01 9413
## # ... with 74 more rows