Reputation: 1016
I have an irregular time series called x:
structure(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 22, 34, 56, 25, 78, 10, 0,
54, 55, 55, 55, 0, 0, 0, 0, 67, 0, 78, 99, 10, 10), index = structure(c(1167814140,
1167814740, 1167815340, 1167815940, 1167816540, 1167817140, 1167817740,
1167818340, 1167818940, 1167819540, 1167820140, 1167820740, 1167821340,
1167821940, 1167822540, 1167823140, 1167823740, 1167824340, 1167825000,
1167825600, 1167826200, 1167826800, 1167827400, 1167828000, 1167828600,
1167829200, 1167829800, 1167830400, 1167831000, 1167831600, 1167832200
), class = c("POSIXct", "POSIXt")), class = "zoo")
I want to convert x into a regular time series aggregating values every 10, 15, 30, 60 minutes. The new time series should always start from 0 minutes (adding NA if necessary). Also, the aggregation should work calculating the cumulative value over the precedent period.
I have tried:
x10 <- to.minutes10(x)
x15 <- to.minutes15(x)
x30 <- to.minutes30(x)
x60 <- to.hourly(x)
However to.period does not return what I need.
EXAMPLE
to.minutes15(x)
x.Open x.High x.Low x.Close
2007-01-03 08:59:00 1 2 1 2
2007-01-03 09:09:00 3 3 3 3
2007-01-03 09:29:00 4 5 4 5
2007-01-03 09:39:00 6 6 6 6
2007-01-03 09:59:00 7 8 7 8
2007-01-03 10:09:00 9 9 9 9
2007-01-03 10:29:00 10 22 10 22
2007-01-03 10:39:00 34 34 34 34
...
But I was expecting:
2007-01-03 09:00:00 3
2007-01-03 09:15:00 3
2007-01-03 09:30:00 9
2007-01-03 09:45:00 6
2007-01-03 10:00:00 15
2007-01-03 10:15:00 9
2007-01-03 10:30:00 32
...
Any idea?
Upvotes: 1
Views: 305
Reputation: 25608
to.period
does not perform an aggregation, it just converts your time series to the desired frequency. To do aggregation, use zoo.aggregate
. There's also a handy function align.time
in xts
package, that takes care of the by
argument:
as.xts(aggregate(x, align.time(index(x), 15*60)))
[,1]
2007-01-03 09:00:00 3
2007-01-03 09:15:00 3
2007-01-03 09:30:00 9
2007-01-03 09:45:00 6
2007-01-03 10:00:00 15
2007-01-03 10:15:00 9
2007-01-03 10:30:00 32
2007-01-03 10:45:00 34
2007-01-03 11:00:00 81
2007-01-03 11:15:00 78
2007-01-03 11:30:00 10
2007-01-03 11:45:00 54
2007-01-03 12:00:00 55
2007-01-03 12:15:00 110
2007-01-03 12:30:00 0
2007-01-03 12:45:00 0
2007-01-03 13:00:00 0
2007-01-03 13:15:00 67
2007-01-03 13:30:00 78
2007-01-03 13:45:00 109
2007-01-03 14:00:00 10
Upvotes: 1