【发布时间】:2012-05-12 12:08:38
【问题描述】:
我在 csv 文件 C:\SampleData.csv 中有一个不规则的时间序列(带有 DateTime 和 RainfallValue):
DateTime,RainInches
1/6/2000 11:59,0
1/6/2000 23:59,0.01
1/7/2000 11:59,0
1/13/2000 23:59,0
1/14/2000 0:00,0
1/14/2000 23:59,0
4/14/2000 3:07,0.01
4/14/2000 3:12,0.03
4/14/2000 3:19,0.01
12/31/2001 22:44,0
12/31/2001 22:59,0.07
12/31/2001 23:14,0
12/31/2001 23:29,0
12/31/2001 23:44,0.01
12/31/2001 23:59,0.01
注意:不规则的时间步长可以是 1 分钟、15 分钟、1 小时等。此外,在所需的 15 分钟间隔内可能会有多个观测值。
我正在尝试创建一个从 2000 年 1 月 1 日到 2001 年 12 月 31 日的常规 15 分钟时间序列,应该如下所示:
2000-01-01 00:15:00 0.00
2000-01-01 00:30:00 0.00
2000-01-01 00:45:00 0.00
...
2001-12-31 23:30:00 0.01
2001-12-31 23:45:00 0.01
注意:时间序列是规则的,间隔为 15 分钟,缺失的数据用 0 填充。如果在 15 分钟的间隔中有多个数据点,则将它们相加。
这是我的代码:
library(zoo)
library(xts)
filename = "C:\\SampleData.csv"
ReadData <- read.zoo(filename, format = "%m/%d/%Y %H:%M", sep=",", tz="UTC", header=TRUE) # read .csv as a ZOO object
RawData <- aggregate(ReadData, index(ReadData), sum) # Merge duplicate time stamps and SUM the corresponding data (CAUTION)
RawDataSeries <- as.xts(RawData,order.by =index(RawData)) #convert to an XTS object
RegularTimes <- seq(as.POSIXct("2000-01-01 00:00:00", tz = "UTC"), as.POSIXct("2001-12-31 23:45:00", tz = "UTC"), by = 60*15)
BlankTimeSeries <- xts((rep(0,length(RegularTimes))),order.by = RegularTimes)
MergedTimeSeries <- merge(RawDataSeries,BlankTimeSeries)
TS_sum15min <- period.apply(MergedTimeSeries,endpoints(MergedTimeSeries, "minutes", 15), sum, na.rm = TRUE )
TS_align15min <- align.time( TS_sum15min [endpoints(TS_sum15min , "minutes", 15)], n=60*15)
问题:输出时间序列TS_align15min:
(a) 具有重复的时间戳块
(b) 从 1999 年开始(神秘地),如:
1999-12-31 19:15:00 0
1999-12-31 19:30:00 0
1999-12-31 19:45:00 0
1999-12-31 20:00:00 0
1999-12-31 20:15:00 0
1999-12-31 20:30:00 0
我做错了什么?
感谢您的任何指导!
【问题讨论】:
-
为我们生成一些可重现的代码,dput() 很有用。还要声明你使用带有 library 或 require 的贡献包。
-
@mdsumner 感谢您的建议。我添加了可重现的示例数据和代码。
-
不,如果它依赖于我们没有的数据文件,它是不可重现的。请参阅我对具有给定种子的 随机数据 的回答——这使得它可以重现。
-
@DirkEddelbuettel 是的,您的代码使答案可重现。我的数据/代码使问题可重现。谢谢!
标签: r time-series xts zoo