Hi @sai_matcha,
Does this reprex do what you require?
id <- c(1,1,1,2,2,2,2,3,3,4,4,4)
time <- c(0,2,4,0,4,7,10,0,5,0,3,8)
dv <- c(NA,2,4,NA,4,8,9,NA,5,NA,6,6)
tad <- c(1,0,3,1,2,0,5,0,1,1,6,0)
df <- data.frame(id,time,dv,tad)
df
#> id time dv tad
#> 1 1 0 NA 1
#> 2 1 2 2 0
#> 3 1 4 4 3
#> 4 2 0 NA 1
#> 5 2 4 4 2
#> 6 2 7 8 0
#> 7 2 10 9 5
#> 8 3 0 NA 0
#> 9 3 5 5 1
#> 10 4 0 NA 1
#> 11 4 3 6 6
#> 12 4 8 6 0
for(ii in 2:length(df$tad)) {
ifelse(df$tad[ii] == 0,
df[ii-1,] <- df[ii,],
df[ii-1,] <- df[ii-1,])
}
df
#> id time dv tad
#> 1 1 2 2 0
#> 2 1 2 2 0
#> 3 1 4 4 3
#> 4 2 0 NA 1
#> 5 2 7 8 0
#> 6 2 7 8 0
#> 7 3 0 NA 0
#> 8 3 0 NA 0
#> 9 3 5 5 1
#> 10 4 0 NA 1
#> 11 4 8 6 0
#> 12 4 8 6 0
Created on 2020-11-30 by the reprex package (v0.3.0)
This solution won't win any prizes for elegance! Would be good to see how this could be achieved in dplyr
.
HTH