Fill value backwards from occurence by group

Viewed 173

Problem: How can I fill backwards all rows in a group before an occurrence of a certain value. I am not trying to fill in NA or missing value using zoo na.locf. In the following I would like to fill all previous rows in A with 1.00 before the 1.00 occurs by each ID group, ideally using dplyr.

Input:

data<- data.frame(ID=c(1,1,1,1,2,2,2,3,3,3,4,4,4,4,4), 
              time=c(1,2,3,4,1,2,3,1,2,3,1,2,3,4,5),
              A=c(0.10,0.25,1,0,0.25,1,0.25,0,1,0.10,1,0.10,0.10,0.10,0.05))
ID time    A
1    1     0.10
1    2     0.25
1    3     1.00
1    4     0.00
2    1     0.25
2    2     1.00
2    3     0.25
3    1     0.00
3    2     1.00
3    3     0.10
4    1     1.00
4    2     0.10
4    3     0.10
4    4     0.10
4    5     0.05

Desired output:

ID time    A
1    1     1.00
1    2     1.00
1    3     1.00
1    4     0.00
2    1     1.00
2    2     1.00
2    3     0.25
3    1     1.00
3    2     1.00
3    3     0.10
4    1     1.00
4    2     0.10
4    3     0.10
4    4     0.10
4    5     0.05
2 Answers
Related