4

我正在以 5 分钟的时间间隔处理时间序列数据。缺少一些 5 分钟的时间序列。我想重新采样数据集以用 NaN 值填充缺失的 5 分钟时间段。我在这里找到了有关如何处理此问题的重要信息:R: Insert rows for missing dates/times

我创建了一个带有 POSIXct 时间序列列“时间”的 data.frame “df”。

padr 包中的 pad 函数允许用户按分钟、小时、天等设置间隔。

interval
返回的日期时间变量的间隔。当为 NULL 时,间隔 > 将等于 datetime 变量的间隔。指定时,它只能小于输入数据的间隔。查看详细信息。

padr 的 pad 函数将在我的 5 分钟数据上创建 1 分钟的间隔。如何设置我自己的用户定义间隔(例如 5 分钟)?

4

3 回答 3

5

新版本昨天击中 CRAN。您现在可以在每个间隔中使用不同于 1 的单位

library(padr)
library(dplyr)
coffee %>% thicken("5 min") %>% select(-time_stamp) %>% pad()
于 2017-05-16T08:25:18.920 回答
2

尝试使用该函数填充到分钟,然后聚合到您想要的规范。然后这会导致自定义摘要

library(padr)
account <- data.frame(day     = as.Date(c('2016-10-21', '2016-10-23', '2016-10-26')),
                      balance = c(304.46, 414.76, 378.98))

account %>% 
  pad('min') %>%   ##pad to the minute
  mutate(five_min = cut(day, "5 min")) %>%   ##create new 'five_min' column
  group_by(five_min) %>%     ## group by the new col
  summarise(ttl = sum(balance, na.rm=TRUE))  ##aggregate the new sum
# # A tibble: 1,441 × 2
#               five_min    ttl
#                 <fctr>  <dbl>
# 1  2016-10-21 00:00:00 304.46
# 2  2016-10-21 00:05:00   0.00
# 3  2016-10-21 00:10:00   0.00
# 4  2016-10-21 00:15:00   0.00
# 5  2016-10-21 00:20:00   0.00
# 6  2016-10-21 00:25:00   0.00
# 7  2016-10-21 00:30:00   0.00
# 8  2016-10-21 00:35:00   0.00
# 9  2016-10-21 00:40:00   0.00
# 10 2016-10-21 00:45:00   0.00
# # ... with 1,431 more rows
于 2017-03-03T19:31:41.820 回答
2

虽然我无法让 Pierre 的解决方案与我的数据格式一起运行(我没有帮助指定),但我能够通过采用 Pierre 的策略来选择填充的 1 分钟间隔的 5 分钟子集来创建解决方案数据。我对这个新的 padr 库感到很兴奋,并希望未来能添加更多功能。

我的策略如下:

library(padr)
library(zoo)
dfpad <- pad(df, interval = "min") #resample timeseries df to 1 min intervals
dfpadzoo <- zoo(dfpad,order.by = dfpad$time) #convert padded df to zoo timeseries
sensStart <- start(dfpadzoo) #first time in data using zoo function
sensEnd <- end(dfpadzoo) # last time in data using zoo function
nexttime <- df$time[2] #identify the time in the second data row
#determine time interval in minutes:
tint_min <- as.double(difftime(nexttime,sensStart, tz="UTC",units="mins"))
#Generate regularly-spaced time series from the start to end of data:
timeFill <- seq(from = as.POSIXct(sensStart, tz="UTC"),
                to = as.POSIXct(sensEnd, tz="UTC"), by = 60*tint_min)
#Create subset of dfpad spaced at 5-minute intervals
sensdatazoo <- dfpadzoo[timeFill]

通过将 df 转换为 zoo 对象,我能够使用 zoo 库中的其他时间序列功能。

于 2017-03-03T21:46:14.920 回答