I have an hourly time-series of rain at four locations for one year as follow. I want to compute sum or mean for all the 24 hours of the day for entire year separate for all the four locations. This is common analysis in Meteorology and termed as diurnal variation. This will give me an idea of which hours are preferred for rainfall at these locations. Is there a simple way to do this in xts/zoo package?
head(rg_hr_xts)
rg1 rg2 rg3 rg4
2018-06-01 00:59:17 1.0 0.0 0 0
2018-06-01 01:59:17 0.2 0.0 0 0
2018-06-01 02:59:17 0.0 0.2 0 0
2018-06-01 03:59:17 0.0 1.6 0 0
2018-06-01 04:59:17 0.0 3.4 0 0
2018-06-01 05:59:17 0.0 0.8 0 0
Note: I have used .indexhour(rg_hr_xts)
which gives me hour of each index as follow
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
20 21 22 23 0 1 2 3 4 5 6 7
I want to sum all the hours with above index 0, 1, 2 and get a dataframe with hour index 0-23 and sum of rainfall for that hour.
I expect following structure of output dataframe:
hour rg1 rg2 rg3 rg4
0 0.3 0.7 1.2 0.4
1 1.3 1.5 1.3 1.3
2 1.5 1.7 1.9 1.8
3 2.0 2.5 2.6 2.9
4 2.1 2.9 3.5 3.6
You can use aggregate()
to calculate sums by hour of the day.
library(xts)
# Some reproducible example data
n <- 1e4
set.seed(21)
x <- .xts(cbind(rg1 = runif(n), rg2 = runif(n)), 1:n * 3600 + runif(n)*100)
# Aggregate by hour of the day
y <- aggregate(x, by = .indexhour(x), FUN = sum)
The result of aggregate()
will be a zoo object with an index of the hour of the day. Then you can use data.frame()
to convert that to a data.frame.
data.frame(hour = index(y), y)
# hour rg1 rg2
# 0 0 214.3876 211.5131
# 1 1 215.5521 205.4340
# 2 2 206.1494 211.7510
# 3 3 223.9533 209.5391
# 4 4 202.8989 211.6612
# 5 5 198.6387 203.7809
# 6 6 218.7807 218.9829
# 7 7 205.2797 214.6127
# 8 8 207.2061 219.2323
# 9 9 217.2509 208.9815
# 10 10 218.4591 202.3216
# 11 11 205.6799 219.2482
# 12 12 206.8984 209.7392
# 13 13 209.4091 205.2837
# 14 14 212.0559 213.2387
# 15 15 211.8372 204.3384
# 16 16 206.5818 221.5508
# 17 17 212.1076 214.9638
# 18 18 219.3799 205.4536
# 19 19 202.6254 202.2210
# 20 20 208.5686 208.5411
# 21 21 213.2116 218.9530
# 22 22 210.6371 207.5539
# 23 23 197.8964 203.9069