I'm currently experiencing a problem with my code. Being a beginner, I can't really find a solution.
library(data.table)
id<- c(rep(1,5), rep(2,5),rep(3,5))
time <-c (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
death <-c(0,1,0,1,1,0,0,1,1,0,0,1,1,0,1)
table<-data.table(id, time, death)
And I would like to obtain a last column that looks like this :
death_ideal<-c(0,1,1,1,1,0,0,1,1,1,0,1,1,1,1)
The idea is that when an "id" is death, it stays dead. For example, id ==1 dies in time 2, so it can not be "un-dead" in time 3. I have tried the code below. It is a bit complicated and it doesn't work (the error obtained is below).
j<- min(table$id)
while(j<=max(table$id)){
i<-min(table$time[which(table$id==j)])
while (i<=max(table$time[which(table$id==j)])){
if (table$death[which(table$time == i)]==1){table$test[which(table$time == i)]<-1}
else {if (table$test[which(table$time == i-1)]==1)
{table$test[which(table$time == i)]<-1}
else { table$test<-0 }}
i = i+1}
j = j+1}
Errors that I get :
Error in if (table$test[which(table$time == i - 1)] == 1) { :
argument is of length zero
In addition: Warning message:
In if (table$death[which(table$time == i)] == 1) { :
the condition has length > 1 and only the first element will be used
It seems that it is a rather common error but, despite that, I can't make my code work. Thank you very much to the person that can help me !