I have sample data:
testSample <- data.table(a = rnorm(n = 20, mean = 2, sd = 1),
b = sample(c(0,1), replace=TRUE, size=20))
testSample
a b
1: 3.1731458 0
2: 1.0687438 1
3: 2.9078655 1
4: 1.5675078 0
5: 2.7825992 0
6: 1.3672285 1
7: 3.6178619 0
8: 2.9067640 1
9: 2.5021129 0
10: 2.7672849 1
11: 2.3501007 1
12: -0.2923344 0
13: 0.3920071 1
14: 2.5113855 0
15: 2.2192234 1
16: 0.5913632 0
17: 0.8864734 1
18: 1.9187394 0
19: 1.1238824 1
20: 1.5001240 1
In column 'b' there are runs of alternating 0 and 1. Along each consecutive run of 1, I want a new column 'c' to be filled with the number from the column "a" at the index of the first 1 in each run.
When 'b' is 0, 'c' should be NA
Desired output where I filled in the new 'c' column manually:
a b c
1: 3.1731458 0 NA
2: 1.0687438 1 1.0687438 # <- run of 1.
3: 2.9078655 1 1.0687438 # <- All rows filled with the first 'a' value in the run
4: 1.5675078 0 NA
5: 2.7825992 0 NA
6: 1.3672285 1 1.3672285 # <-
7: 3.6178619 0 NA
8: 2.9067640 1 2.9067640 # <-
9: 2.5021129 0 NA
10: 2.7672849 1 2.7672849 # <- run of 1
11: 2.3501007 1 2.7672849 # <- All rows filled with the first 'a' value in the run
12: -0.2923344 0 NA
13: 0.3920071 1 0.3920071
14: 2.5113855 0 NA
15: 2.2192234 1 2.2192234
16: 0.5913632 0 NA
17: 0.8864734 1 0.8864734
18: 1.9187394 0 NA
19: 1.1238824 1 1.1238824
20: 1.5001240 1 1.1238824