2014-01-21 85 views
2

您好我有一個數據幀象下面這樣:如何指示第一個事件觀察並刪除縱向數據框中的其餘事件觀察值?

id=rep(c(1:3),each=3) 
status=rep(c(1,0,1),each=3) 
event=c(0,1,1,0,0,0,1,1,1) 
cbind(id,status,event) 
     id status event 
    [1,] 1  1  0 
    [2,] 1  1  1 
    [3,] 1  1  1 
    [4,] 2  0  0 
    [5,] 2  0  0 
    [6,] 2  0  0 
    [7,] 3  1  1 
    [8,] 3  1  1 
    [9,] 3  1  1 

我想保持或指示是「事件」 == 1如下「事件」 == 1的第一行之前的行:

id status event ind 
1 1  0  T 
1 1  1  T 
1 1  1  F 
2 0  0  T 
2 0  0  T 
2 0  0  T 
3 1  1  T 
3 1  1  F 
3 1  1  F 

id status event 
1 1  0  
1 1  1  
2 0  0  
2 0  0  
2 0  0  
3 1  1  

任何人有什麼好主意? 非常感謝!

回答

3

如果DF然後輸入數據幀:

DF$ind <- ave(DF$event == 1, DF$id, FUN = function(x) !cumsum(c(0, head(x, -1)))) 

在它給出了示例的情況下:

> DF 
    id status event ind 
1 1  1  0 TRUE 
2 1  1  1 TRUE 
3 1  1  1 FALSE 
4 2  0  0 TRUE 
5 2  0  0 TRUE 
6 2  0  0 TRUE 
7 3  1  1 TRUE 
8 3  1  1 FALSE 
9 3  1  1 FALSE 
0

這種方法使用由plyr id分裂的data.frame。然後event==0event==1的情況分開處理,然後再組合。如果對於給定的id值沒有任何event==1行,則包括檢查。

require(plyr) 

SelectRecords <- function(d) { 
    eventIsZero <- which(d$event==0) 
    eventIsOne <- which(d$event==1) 

    if(length(eventIsOne) >= 1) 
    selectedIndices <- c(eventIsZero, min(eventIsOne, na.rm=T)) 
    else  
    selectedIndices <- eventIsZero 

    return(d[selectedIndices, ]) 
} 

ddply(ds, .variables="id", .fun=SelectRecords)