Reputation: 71
For example, how can I take what's in x1 and turn it into x2 in an efficient way? I'm working with a large data set so for loops are not preferable.
x1 x2
1 FALSE 1
2 FALSE 2
3 TRUE 3
4 TRUE 3
5 FALSE 4
6 FALSE 5
7 FALSE 6
8 TRUE 7
9 TRUE 7
10 FALSE 8
11 FALSE 9
12 FALSE 10
13 FALSE 11
14 FALSE 12
15 FALSE 13
16 FALSE 14
17 FALSE 15
18 FALSE 16
19 TRUE 17
20 TRUE 17
21 FALSE 18
22 FALSE 19
23 FALSE 20
24 FALSE 21
Upvotes: 0
Views: 34
Reputation: 388982
One base R way would be to increment value by 1 when there is FALSE
or the value changes from the previous value.
with(df, cumsum(!x1 | c(TRUE, diff(x1) != 0)))
#[1] 1 2 3 3 4 5 6 7 7 8 9 10 11 12 13 14 15 16 17 17 18 19 20 21
data
df <- structure(list(x1 = c(FALSE, FALSE, TRUE, TRUE, FALSE, FALSE,
FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE)), row.names = c(NA,
-24L), class = "data.frame")
Upvotes: 1