【发布时间】:2021-04-04 19:22:47
【问题描述】:
【问题讨论】:
标签: r time-series
【问题讨论】:
标签: r time-series
一种简单的方法是使用tsibble 包中的fill_gaps() 函数:
library(tsibble)
library(dplyr)
df1 <- tibble(
row = 1:100,
lane = rnorm(100),
count = sample(1:5, size=100, replace=TRUE),
timestamp = seq(as.POSIXct("2019-11-02 00:00:00"), by= "1 min", length=100)
) %>%
filter(row <= 30 | row >= 36) %>%
select(-row)
df1[26:35,]
#> # A tibble: 10 x 3
#> lane count timestamp
#> <dbl> <int> <dttm>
#> 1 0.218 4 2019-11-02 00:25:00
#> 2 -1.63 4 2019-11-02 00:26:00
#> 3 0.603 5 2019-11-02 00:27:00
#> 4 -1.04 4 2019-11-02 00:28:00
#> 5 -0.397 5 2019-11-02 00:29:00
#> 6 0.179 5 2019-11-02 00:35:00
#> 7 0.391 4 2019-11-02 00:36:00
#> 8 1.09 5 2019-11-02 00:37:00
#> 9 0.119 2 2019-11-02 00:38:00
#> 10 0.949 3 2019-11-02 00:39:00
df2 <- df1 %>%
as_tsibble(index=timestamp) %>%
fill_gaps(count=0)
df2[26:35,]
#> # A tsibble: 10 x 3 [1m] <?>
#> lane count timestamp
#> <dbl> <dbl> <dttm>
#> 1 0.218 4 2019-11-02 00:25:00
#> 2 -1.63 4 2019-11-02 00:26:00
#> 3 0.603 5 2019-11-02 00:27:00
#> 4 -1.04 4 2019-11-02 00:28:00
#> 5 -0.397 5 2019-11-02 00:29:00
#> 6 NA 0 2019-11-02 00:30:00
#> 7 NA 0 2019-11-02 00:31:00
#> 8 NA 0 2019-11-02 00:32:00
#> 9 NA 0 2019-11-02 00:33:00
#> 10 NA 0 2019-11-02 00:34:00
由reprex package (v0.3.0) 于 2020 年 12 月 28 日创建
【讨论】:
如果该列是Datetime 类,则从complete 中的1 minute 中的1 minute 从min 和max 的'timestamp' 列的值创建一个sequence,同时将count 指定为0 表示原始数据集中将丢失的元素
library(tidyr)
library(dplyr)
df2 <- complete(df1, timestamp = seq(min(timestamp),
max(timestamp), by = "1 min"), fill = list(count = 0))
如果我们需要用相同的值填充lane 列,请使用fill
df2 <- complete(df1, timestamp = seq(min(timestamp),
max(timestamp), by = "1 min"), fill = list(count = 0)) %>%
fill(lane)
注意:如果列'timestamp'不是Datetime类,可以用as.POSIXct转换成POSIXct
df1$timestamp <- as.POSIXct(df1$timestamp)
在执行complete 步骤之前
【讨论】:
df2 <- complete(df1, ...