在R中将不规则时间序列更改为常规时间序列1分钟

时间:2016-10-24 22:13:53

标签: r time xts series zoo

我有一个名为dts的时间序列,它是不规则的时间序列。

                Date| V1
1994-02-08 01:09:00 | 0.1
1994-02-08 01:18:00 | 0.1
1994-02-08 01:41:00 | 0.1
1994-02-08 01:46:00 | 0.1
1994-02-08 01:50:00 | 0.1
1994-02-08 01:57:00 | 0.1
1994-02-12 20:27:00 | 0.1
1994-02-12 20:28:00 | 0.1
1994-02-12 20:30:00 | 0.1
1994-02-12 20:30:00 | 0.1 

我想定期并每1分钟安排一次。所需的结果应该是:

                Date| V1
1994-02-08 01:09:00 | 0.1
1994-02-08 01:10:00 | 0.0
1994-02-08 01:11:00 | 0.0
1994-02-08 01:12:00 | 0.0
1994-02-08 01:13:00 | 0.0
1994-02-08 01:14:00 | 0.0
1994-02-08 01:15:00 | 0.0
1994-02-08 01:16:00 | 0.0
1994-02-08 01:17:00 | 0.0
1994-02-08 01:18:00 | 0.1 

为了在常规时间序列上应用移动平均函数,我想使它成为常规。任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:2)

library(xts)

# Create evenly spaced timestamps at frequency you desire (keep it simple to 1 hour here):
ts.1min <- seq(as.POSIXct("2016-10-12 12:00:00"), as.POSIXct("2016-10-12 13:00:00"), by = paste0("60 s"))

# Generate your data for 10 random timestamps in the 1 hour interval:
set.seed(1)
x.toy <- xts(round(rnorm(10, mean = 0, sd = 0.2), 1), 
             ts.1min[sample(x = 1:length(ts.1min), size = 10, replace = FALSE)], dimnames = list(NULL, "V1"))

# > x.toy
# V1
# 2016-10-12 12:00:00  0.1
# 2016-10-12 12:07:00  0.3
# 2016-10-12 12:12:00  0.0
# 2016-10-12 12:15:00  0.1
# 2016-10-12 12:17:00 -0.1
# 2016-10-12 12:20:00  0.1
# 2016-10-12 12:21:00 -0.2
# 2016-10-12 12:38:00 -0.2
# 2016-10-12 12:46:00  0.1
# 2016-10-12 12:57:00 -0.1


# Fill timestamps with no value as 0:
x.res <- merge(x.toy, xts(, ts.1min), fill = 0)

# > head(x.res, 10)
# V1
# 2016-10-12 12:00:00 0.1
# 2016-10-12 12:01:00 0.0
# 2016-10-12 12:02:00 0.0
# 2016-10-12 12:03:00 0.0
# 2016-10-12 12:04:00 0.0
# 2016-10-12 12:05:00 0.0
# 2016-10-12 12:06:00 0.0
# 2016-10-12 12:07:00 0.3
# 2016-10-12 12:08:00 0.0
# 2016-10-12 12:09:00 0.0