1) 假设系列从下午 3 点开始,那几天是连续的,并且从下午 3 点到晚上 10 点的所有时间都存在:
tser <- ts(DF[-1], freq = 8)
给予:
> tser
Time Series:
Start = c(1, 1)
End = c(1, 8)
Frequency = 8
hour Count Year Month Day
1.000 15 69 2001 1 1
1.125 16 12 2001 1 1
1.250 17 56 2001 1 1
1.375 18 34 2001 1 1
1.500 19 44 2001 1 1
1.625 20 91 2001 1 1
1.750 21 82 2001 1 1
1.875 22 49 2001 1 1
这将表示第 1 天 3pm 为 1.0,第 1 天 4pm 为 1+1/8,第 1 天 5pm 为 1+2/8,...,第 1 天 10pm 为 1+7/8,第 2 天的索引下午 3 点为 2,第 2 天下午 4 点为 2+1/8,等等。
2) 相同,但天数从 1970-01-01 以来的天数开始,而不是从 1 开始:
tser <- ts(DF[-1], start = as.Date("2001-01-01"), freq = 8)
给予:
> tser
Time Series:
Start = c(11323, 1)
End = c(11323, 8)
Frequency = 8
hour Count Year Month Day
11323.00 15 69 2001 1 1
11323.12 16 12 2001 1 1
11323.25 17 56 2001 1 1
11323.38 18 34 2001 1 1
11323.50 19 44 2001 1 1
11323.62 20 91 2001 1 1
11323.75 21 82 2001 1 1
11323.88 22 49 2001 1 1
也就是说,这将表示每天自 1970 年 1 月 1 日以来的天数加上与以前一样的 0、1/8、...、7/8 小时数。
如果您以后需要重新生成日期/时间,那么:
library(chron)
tt <- as.numeric(time(tser))
as.chron(tt %/% 1) + (8 * tt%%1 + 15)/24
给予:
[1] (01/01/01 15:00:00) (01/01/01 16:00:00) (01/01/01 17:00:00)
[4] (01/01/01 18:00:00) (01/01/01 19:00:00) (01/01/01 20:00:00)
[7] (01/01/01 21:00:00) (01/01/01 22:00:00)
3) 动物园如果让它们保持等间距并不重要,那么你可以试试这个:
library(zoo)
library(chron)
z <- zoo(DF[-1], as.chron(format(DF$Date), "%d.%m.%Y") + DF$hour/24)
给予:
> z
hour Count Year Month Day
(01/01/01 15:00:00) 15 69 2001 1 1
(01/01/01 16:00:00) 16 12 2001 1 1
(01/01/01 17:00:00) 17 56 2001 1 1
(01/01/01 18:00:00) 18 34 2001 1 1
(01/01/01 19:00:00) 19 44 2001 1 1
(01/01/01 20:00:00) 20 91 2001 1 1
(01/01/01 21:00:00) 21 82 2001 1 1
(01/01/01 22:00:00) 22 49 2001 1 1
动物园方法不需要所有时间都在场,也不需要天是连续的。
注意:我不确定您是否真的需要单独拆分所有日期和时间字段,因为它们很容易动态生成,所以这可能就足够了。
Count <- z$Count
年可以通过as.numeric(format(time(Count), "%Y")) 恢复,月、日和小时可以通过使用%m、%d 或%H 代替%Y 恢复。
还可以使用month.day.year(time(Count)) 生成月、日和年列的列表。
years(time(Count))、months(time(Count))、days(time(Count)) 和 hours(time(Count)) 将产生指定数量的因子。