r - R 中的每小时时间序列。 ts(... start) 是如何工作的?

标签 r time-series

试图在 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

看答案 starting a daily time series in 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() 中工作?

我也查了一下帖子:How to Create a R TimeSeries for Hourly data

建议使用 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)```

关于r - R 中的每小时时间序列。 ts(... start) 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50330772/

相关文章:

r - 从 Rdata 文件中获取特定对象

滚动应用于向量的子集

r - R在哪里存储临时文件

python - 非均匀间隔时间序列的季节性分解,R 或 Python 中任何完善的算法?

mysql - d3js : data/column required for time series chart with dropdown list

mysql - 缩小不断增长的时间相关 Mysql 表的大小

R Markdown : place an Appendix after the "References" section?

r - 如何重新排序组合 ggplot2 图中的图?

python - 使用 numpy 或 pandas 的时间序列

r - 如何申报每周数据的时间序列?