Fill value backwards from occurence by group with condition

Viewed 226

Problem: I would like to fill a value backwards from occurrence by group with a condition. I am trying to generate column C in the desired output.

Set C equal to B and fill 1 backwards if A is <= 35, stop fill if A > 35.

I am trying to complete this task using dplyr.

Building on something similar to my previous question: Fill value backwards from occurence by group

Input:

DAT_in  = 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(100,35,25,0,
                      100,75,55,
                      100,28,25,
                      100,30,45,25,0),
                  B=c(0,0,0,1,
                      0,0,0,
                      0,0,1,
                      0,0,0,0,1))

Desired output (C):

DAT_out  = 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(100,35,25,0,
                  100,75,55,
                  100,28,25,
                  100,30,45,25,0),
              B=c(0,0,0,1,
                  0,0,0,
                  0,0,1,
                  0,0,0,0,1),
              C=c(0,1,1,1,
                  0,0,0,
                  0,1,1,
                  0,0,0,1,1))
3 Answers
Related