r - 用 R 插值不规则时间序列
问题描述
在 R 中搜索时间序列数据的线性插值时,我经常na.approx()
从zoo
包中找到要使用的建议。
但是,对于不规则的时间序列,我遇到了问题,因为插值均匀分布在间隙的数量上,而不考虑值的关联时间戳。
我找到了一个解决方法 using approxfun()
,但我想知道是否有更清洁的解决方案,理想情况下基于具有包系列tsibble
功能的对象?tidyverts
以前的答案依赖于通过填补空白将不规则日期网格扩展到规则网格。但是,当在插值期间应考虑白天时,这会导致问题。
这是一个(修订后的)最小示例,带有 POSIXct 时间戳,而不是仅日期:
library(tidyverse)
library(zoo)
df <- tibble(date = as.POSIXct(c("2000-01-01 00:00", "2000-01-02 02:00", "2000-01-05 00:00")),
value = c(1,NA,2))
df %>%
mutate(value_int_wrong = na.approx(value),
value_int_correct = approxfun(date, value)(date))
# A tibble: 3 x 4
date value value_int_wrong value_int_correct
<dttm> <dbl> <dbl> <dbl>
1 2000-01-01 00:00:00 1 1 1
2 2000-01-02 02:00:00 NA 1.5 1.27
3 2000-01-05 00:00:00 2 2 2
任何想法如何(有效地)处理这个?谢谢你的支持!
解决方案
这是一个等效的基于 tsibble 的解决方案。该interpolate()
函数需要一个模型,但您可以使用随机游走在点之间进行线性插值。
library(tidyverse)
library(tsibble)
library(fable)
#> Loading required package: fabletools
df <- tibble(
date = as.Date(c("2000-01-01", "2000-01-02", "2000-01-05", "2000-01-06")),
value = c(1, NA, 2, 1.5)
) %>%
as_tsibble(index = date) %>%
fill_gaps()
df %>%
model(naive = ARIMA(value ~ -1 + pdq(0,1,0) + PDQ(0,0,0))) %>%
interpolate(df)
#> # A tsibble: 6 x 2 [1D]
#> date value
#> <date> <dbl>
#> 1 2000-01-01 1
#> 2 2000-01-02 1.25
#> 3 2000-01-03 1.5
#> 4 2000-01-04 1.75
#> 5 2000-01-05 2
#> 6 2000-01-06 1.5
由reprex 包(v0.3.0)于 2020 年 4 月 8 日创建
推荐阅读
- ios - WKWebView 中的蒙版图像受 CORS 限制
- mysql - 如何在 SQL 中创建两个连续的 Group By
- pygame - Pygame 错误'pow 预期 2 个参数,得到 1'
- ios - 打开动态链接时如何重定向到某个屏幕?
- android - 无法在空对象上调用方法 doFirst():react.gradle
- node.js - 从连接表中选择列 - TypeOrm
- ios - Swift 2D 阵列性能
- c - 如何在C中的单行上制作倒数计时器打印结果?
- cassandra - Debezium MongoDB 源 JSON 接收到 Cassandra (LENSES.IO)
- python-3.x - 我在使用 python 时遇到问题,我正在尝试制作 QRcode 创建应用程序