按时间序列填写时间频率表

时间:2018-02-23 07:06:38

标签: r time-series

考虑一个时间频率表

2008-01-01 2008-01-03 2008-01-05 2008-01-06 2008-01-07 2008-01-08
         1          8          2          2          3          1

请注意,2008-01-02和2008-01-04将丢失。

预期结果如下:

2008-01-01 2008-01-02 2008-01-03 2008-01-04 2008-01-05 2008-01-06 2008-01-07 2008-01-08
         1          0          8          0          2          2          3          1

或以日期框架的形式:

   Time    Frequency
2008-01-01    1
2008-01-02    0
2008-01-03    8
2008-01-04    0
2008-01-05    2
2008-01-06    2
2008-01-07    3
2008-01-08    1

1 个答案:

答案 0 :(得分:2)

更好的选择是转换为factor并指定levels,然后执行table

rndates <- range(dates)
table(factor(dates, levels = as.character(seq(rndates[1], rndates[2], by = "1 day"))))
#  2008-01-01 2008-01-02 2008-01-03 2008-01-04 2008-01-05 2008-01-06 2008-01-07 2008-01-08 
#        4          0          7          0          1          5          6          2 

数据

set.seed(24)
dates <- sample(as.Date(c("2008-01-01", "2008-01-03", "2008-01-05", 
    "2008-01-06", "2008-01-07", "2008-01-08")), 25, replace = TRUE)