Total_Solar_Gesamt <- read.table(header=TRUE, sep=",", text="
Timedate, TotalSolar_MW
2013-06-01 04:45:00, 13.0
2013-06-01 05:00:00, 41.7
2013-06-01 05:15:00, 81.8
2013-06-01 05:30:00, 153.0
2013-06-01 05:45:00, 270.7
2013-06-01 06:00:00, 429.3
2013-06-01 06:15:00, 535.4
")
用于cut.POSIXt
将日期划分为每小时间隔:
Sum <- aggregate(Total_Solar_Gesamt["TotalSolar_MW"],
list(hour=cut(as.POSIXct(Total_Solar_Gesamt$Timedate), "hour")),
sum)
Sum
hour TotalSolar_MW
1 2013-06-01 04:00:00 13.0
2 2013-06-01 05:00:00 547.2
3 2013-06-01 06:00:00 964.7
请注意,以上将 06:00:00 与其他 06 时间分组。如果要将一小时的开头与前一小时分组,只需从每个时间戳中减去一秒:
Sum2 <- aggregate(Total_Solar_Gesamt["TotalSolar_MW"],
list(hour=cut(as.POSIXct(Total_Solar_Gesamt$Timedate)-1, "hour")),
sum)
Sum2
hour TotalSolar_MW
1 2013-06-01 04:00:00 54.7
2 2013-06-01 05:00:00 934.8
3 2013-06-01 06:00:00 535.4
而且,如果您想提前一小时报告您的日期,例如您的问题:
Sum2$adjustedHour <- as.POSIXct(Sum2$hour) + 3600
Sum2
hour TotalSolar_MW adjustedHour
1 2013-06-01 04:00:00 54.7 2013-06-01 05:00:00
2 2013-06-01 05:00:00 934.8 2013-06-01 06:00:00
3 2013-06-01 06:00:00 535.4 2013-06-01 07:00:00
使用 xts:
library(xts)
data.xts <- xts(Total_Solar_Gesamt$TotalSolar_MW,
as.POSIXct(Total_Solar_Gesamt$Timedate)-1)
# subtract 1 second, as discussed above
Sum.xts <- period.apply(data.xts, INDEX=endpoints(data.xts, "hours"), FUN=sum)
Sum.xts
[,1]
2013-06-01 04:59:59 54.7
2013-06-01 05:59:59 934.8
2013-06-01 06:14:59 535.4
注意 xts 中的时间戳Sum.xts
是每小时的最后一个时间戳。xts 可以很容易地对齐它们:
Sum.xts <- align.time(Sum.xts, 3600) # round up to next hour
Sum.xts
[,1]
2013-06-01 05:00:00 54.7
2013-06-01 06:00:00 934.8
2013-06-01 07:00:00 535.4