2016-10-24 94 views
1

我有一個叫做dts的時間序列,它是不規則的時間序列。將異常時間序列更改爲常規時間序列1分鐘R

   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

我猜測你所需要的結果中的數據時間戳一次只增加1分鐘,而不是從1994-02-08 01:14:00任意跳轉到4天1994-02-12 01:15:00?我的回答如下 – FXQuantTrader

回答

1
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