Question

I am trying to split several xts objects with one unique irregular time series. split.xts splits on days, minutes, seconds, etc. Using breakpoints requires vectors of equal length, which produces an error when I try to split my data.

dd <- c("2014-02-23","2014-03-12", "2014-05-29")
tt <- c("03:15:52", "03:49:17", "04:03:24", "05:30:19", "05:56:49",
        "06:14:04", "09:42:13", "11:57:25", "11:58:02", "12:12:49",
        "15:38:00", "15:44:21", "16:16:04")
dt <- c(outer(dd,tt,paste))
xx <- as.xts(seq_along(dt), as.POSIXct(dt))
spltr <- c("2014-01-13 12:09:32", "2014-02-09 06:23:41",
           "2014-03-01 13:35:12", "2014-05-14 07:12:52")

I am trying to split xx by spltr to find the frequency of records in each piece. I tried aggregate(xx,by=spltr,length) but I get an error because spltr is not the same length as xx. split.xts doesn't work because spltr is not regular.

Was it helpful?

Solution

First, merge your xx object with an empty xts object containing your breakpoints.

xs <- merge(xx, xts(,as.POSIXct(spltr)))

Then you can find the 'endpoints' of your spltr object in xs by using the which.i argument to [.xts.

ep <- c(0,xs[as.POSIXct(spltr),which.i=TRUE])

Now you can use period.apply on the xs object (making sure to deal with any potential NA).

> period.apply(xs, ep, function(x) nrow(na.omit(x)))
                    xx
2014-01-13 12:09:32  0
2014-02-09 06:23:41  0
2014-03-01 13:35:12 13
2014-05-14 07:12:52 13
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top