Problem Statement
Given the below data set which has two columns Column1
& Column 2
, add another two more column called Counter
and Counting time
. The conditions to Initialize the counter
and Counter time
is as follows:
- The counter should be incremented only when value in
Column1 > 1
andColumn2 = 0
- The Counter must start to increment after 2 values from the condition satisfied row
- The
Counting time
must contain the values of number of time the sequence has occurred (Sequence of data points that has satisfied the condition)
Data Frame with Expected output
Column1 Column2 Counter Counter_Time
1.1254 2.784 0 0
4.678 7.985 0 0
8.89 0 0 1
7.65 0 0 1
3.54 0 1 1
4.32 0 2 1
9.83 0 3 1
3.86 4.3 0 1
5.63 9.8 0 1
4.53 0 0 2
6.83 0 0 2
3.431 0 4 2
8.976 0 5 2
9.864 0 6 2
7.3 9.2 0 2
2.3 3.2 0 2
4.3 0 0 3
2.1 0 0 3
4.32 0 7 3
I came across similar kind of question got the answer on how to increment the counter but I wasn't able to satisfy the above mentioned conditions. Please note that the Counter should start after the two rows which satisfies the condition.
Observation from the Data Set
- The row number 3 satisfies the condition, The
counter
is not initialized butCounter_Time
has been incremented - The
Counter
has started from the row number 5(According to condition first 2 row from the condition satisfied values should not trigger the counter) - Counter in Row number 8 comes back to 0 and
Counter_Time
remains same - Again, the
Counter
has started to increment from row number 12 by not considering the row 10 and 11. ButCounter_time
was incremented at row 10
I have elaborated the problem statement so that it is clear to the experts to provide accurate solutions.
Update
The following code is an update after
dt2
is created. The idea is to make sure when no rows meet the condition, the code still generates an output withCounter
all equals to 0.A compact solution with
data.table
(using the same data as @ycw):which gives:
Used data: