The rules for your transformation are : Keep the first 0 if its sequence of 0’s is followed by a 1 set the other 0’s to -1. If the sequence of 0’s is followed by a -1 set all the 0’s to -1
Which is equivalent to
Get rid of the -1’s since they are not modified and does not impact the other values. Now our sequence only consists in 0’s and 1’s.
Then, set all 0’s and 1’s that follows an identical value to -1.
x[x!=-1][sequence(rle(as.character(x[x!=-1]))$lengths)!=1] = -1
solved Buy and sell signal to be optimized in r [duplicate]