Skip to main content

probability or statistics - Manually modify lists for survival analysis


I have a series of lists of this form: {1, 1, 1, 1, 0, 0, 1, 1}. I would like to perform a survival analysis on these lists. To do that, I need a code that would check each elements of these lists, do nothing as long as these are 1s, but as soon as one element is 0, it would change all the following elements to zero.


As an example, this code would transform the above list to {1, 1, 1, 1, 0, 0, 0, 0}. I can't seem to find a way to do this. Thanks.



Answer



Let's take


list = {{1, 1, 1, 0, 1, 0, 1}, {1, 1, 1, 1, 1, 1, 1, 1}, {0, 1, 1, 1}, {0, 0}}


and run


list /. {x : 1 ___, z : 0 ___, y___} :> PadRight[{x}, Length@{x, z, y}]


{{1, 1, 1, 0, 0, 0, 0}, {1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0}}





Original answer:


Cases[list, {x : 1 ___, 0, y___} :> PadRight[{x}, Length @ {x, 0, y}]]



{{1, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0}}



Equivalents:


Cases[list, {x : 1 ___, 0, y___} :> Flatten @ {x, 0, ConstantArray[0, Length @ {y}]}]

Cases[list, {x : 1 ___, 0, y___} :> Join @@ {{x}, {0}, ConstantArray[0, Length @ {y}]}]

Fails when a list is composed only of 1s.



UPDATE:


This is a fix:


Cases[list, {Longest[x : 0 .. | 1 ..], y___} :> PadRight[{x}, Length @ {x, y}]]

Comments