[英]hourly time series in R. How ts(… start) works?
試圖在 R 中每小時創建一個時間序列。
我有一個收集每小時車輛數量的數據框,它看起來像:
> head(df)
# A tibble: 6 x 8
interval cars vans trucks total `mean speed` `% occupation` hour
<dttm> <int> <int> <int> <int> <dbl> <dbl> <int>
1 2017-10-09 00:00:00 7 0 0 7 7.37 1. 0
2 2017-10-09 01:00:00 24 0 0 24 16.1 3. 1
3 2017-10-09 02:00:00 27 0 0 27 18.1 2. 2
4 2017-10-09 03:00:00 47 3 0 50 31.5 3. 3
5 2017-10-09 04:00:00 122 1 5 128 48.0 16. 4
6 2017-10-09 05:00:00 353 6 2 361 66.3 20. 5
> tail(df,1)
# A tibble: 1 x 8
interval cars vans trucks total `mean speed` `% occupation` hour
<dttm> <int> <int> <int> <int> <dbl> <dbl> <int>
1 2018-03-15 20:00:00 48 0 2 50 31.5 5. 20
查看在R中開始每日時間序列的答案,該答案清楚地解釋了如何按天創建 ts 我已將此 df 轉換為時間序列:
ts2Start <- df$interval[1]
ts2End <- df$interval[nrow(df)]
indexPerHour <- seq(ts2Start, ts2End, by = 'hour')
由於我們一年有 365 天,每天有 24 小時,因此我將 ts 創建為:
> df.ts <- ts(df$total, start = c(2017, as.numeric(format(indexPerHour[1], '%j'))),
+ frequency=24*365)
在哪里
as.numeric(format(indexPerHour[1], '%j')))
返回 282
為了驗證我在做什么,我檢查了從索引獲得的日期是否與我的數據框中的第一行相同
head(date_decimal(index(df.ts)),1)
但是雖然我的第一個日期/時間應該是:“2017-10-09 00:00:00”,但我得到的是:“2017-01-12 16:59:59 UTC”
看起來df.ts
系列中的第一個索引已經開始於 ~ 282/24
我不明白我做錯了什么。 start 參數如何在ts()
?
我還檢查了帖子: 如何為每小時數據創建 R TimeSeries
建議使用xts
包。
問題是我只是從使用tslm()
並且似乎不支持xts
對象的書中學習。
我可以使用ts()
創建每小時時間序列嗎?
您應該改用 xts 庫。 例如:
time_index <- seq(from = as.POSIXct("2016-01-01 00:00:00"),
to = as.POSIXct("2018-10-01 00:00:00"), by = "hour")
traff = xts(df, order.by = time_index)```
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.