Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split xts object by events

Tags:

split

r

xts

I have an xts object with a handful of event indicators. I need to split it by certain events, so that all entries from a given event up to the next event will be saved in the same xts, eventually creating a list of xts objects, with each containing the event as the last entry with no other events of the same type.

an example:

ts = as.Date(Sys.Date()-99:0)
e1 = numeric(100);e1[10*1:10]=1
e2 = numeric(100);e2[15*1:6]=1
y  = 1:100  # just a sample content
xs = as.xts(cbind(e1,e2,y),order.by=ts)

ee = e1*e2==1  # the event in which both e1 and e2 are 1, should happen at 30,60,90

# here should be splitting function that gets xs and ee as parameters
# and should return a list of 4 xts: the first with the entries 1 through 30, 
# the second with entries 31 to 60, the third with entries 61 to 90, and the last
# with entries 91 to 100

Your suggestions will be greatly appreciated.

like image 590
amit Avatar asked Apr 13 '13 10:04

amit


1 Answers

Use cumsum(ee) to create your grouping variable, then just call split. You have to make a small change to the output of cumsum, since you want the TRUE values to be the last observation in the group (rather than the first).

split(xs, c(0,head(cumsum(ee),-1)))
split(xs,rev(cumsum(rev(ee))))  # grouping factors reversed
like image 149
Joshua Ulrich Avatar answered Nov 15 '22 09:11

Joshua Ulrich