2014-09-02 89 views
0

我具有類似於下面在R.每個受試者的一行的數據集:分割數據集由事件時間

> (fake = data.frame(id=c(1,2,3), x=c(42,61,50), event=c(0,0,1), followup=c(6,2,12))) 

    id x event followup 
1 1 42  0  6 
2 2 61  0  2 
3 3 50  1  12 

我要拆分的數據集到由觀察到的事件的時間定義的時間間隔:

id x event start.time stop.time 
1 1 42  0   0   2 
2 1 42  0   2   6 
3 2 61  0   0   2 
4 3 50  0   0   2 
5 3 50  0   2   6 
6 3 50  1   6  12 

因此,每個受試者都會收到比他自己的隨訪時間更短的所有事件時間間隔。在時間12時有事件的主體3在他還活着的早期時間間隔中接收0。

我該怎麼做?實際的數據集大約有20,000行和900個獨特的事件時間。

回答

0

條件不是很清楚。

res <- do.call(rbind, lapply(split(fake, fake$id), function(x) { 
x1 <- x$followup 
indx <- cumsum(seq(0, 6, by = 2)) 
indx1 <- indx[1:which(indx == x1)] 
indx2 <- rep(indx1, each = 2) 
indx3 <- indx2[-c(1, length(indx2))] 
x2 <- do.call(rbind, lapply(split(indx3, (seq_along(indx3) - 1)%/%2 + 1), function(y) data.frame(id = x$id, 
    x = x$x, event = x$event, start.time = y[1], stop.time = y[2]))) 
if (all(!(!x2$event))) 
    x2$event[-length(x2$event)] <- 0 
x2 
})) 


row.names(res) <- 1:nrow(res) 
res 
# id x event start.time stop.time 
#1 1 42  0   0   2 
#2 1 42  0   2   6 
#3 2 61  0   0   2 
#4 3 50  0   0   2 
#5 3 50  0   2   6 
#6 3 50  1   6  12