2013-04-13 41 views
5

我有一個xts對象,帶有一些事件指示器。我需要將它按特定事件拆分,以便從給定事件直到下一個事件的所有條目都將保存在同一個xts中,最終創建一個xts對象列表,每個對象都包含事件作爲最後一個條目而沒有其他事件同類型的事件。按事件拆分xts對象

一個例子:

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 

您的建議將不勝感激。

回答

4

使用​​來創建您的分組變量,然後只需撥打split。您必須對cumsum的輸出進行小幅更改,因爲您希望TRUE值是組中最後一次觀察結果(而不是第一次)。

split(xs, c(0,head(cumsum(ee),-1))) 
split(xs,rev(cumsum(rev(ee)))) # grouping factors reversed