1

I have a vector Blinks whose values are either 0 or 1:

df <- data.frame(
  Blinks = c(0,0,1,1,1,0,0,1,1,1,1,0,0,1,1)
)

I want to insert a grouping variable for when Blinks == 1. I'm using rleidfor this but the grouping seems to count in the instances where Blinks == 0:

library(dplyr)
library(data.table)
df %>%
  mutate(Blinks_grp = ifelse(Blinks > 0, rleid(Blinks), Blinks))
       Blinks Blinks_grp
    1       0          0
    2       0          0
    3       1          2
    4       1          2
    5       1          2
    6       0          0
    7       0          0
    8       1          4
    9       1          4
    10      1          4
    11      1          4
    12      0          0
    13      0          0
    14      1          6
    15      1          6

How can I obtain the correct result:

    1       0          0
    2       0          0
    3       1          1
    4       1          1
    5       1          1
    6       0          0
    7       0          0
    8       1          2
    9       1          2
    10      1          2
    11      1          2
    12      0          0
    13      0          0
    14      1          3
    15      1          3
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
  • 1
    If `Blinks` is binary won't `rleid(Blinks)/2` do the trick? [Goes to check...] Yes, it will. – Limey Aug 01 '21 at 11:25
  • @Limey ...however not very general, `rleid(c(1, 1, 0, 0, 1, 1)) / 2` – Henrik Aug 01 '21 at 11:34
  • 1
    @Henrik. True. Wrapping in `ceiling()` takes care of the case when the target value is in the first element of the vector. So, with `x <- c(1, 1, 0, 0, 1, 1)`, as in your counter example, `ceiling(ifelse(x > 0, rleid(x)/2, x))` gives the desired result succinctly without changing the result for OP's use case. – Limey Aug 01 '21 at 11:44
  • Indeed! Or slightly more compact `ceiling(rleid(x) * x / 2)`. Cheers – Henrik Aug 01 '21 at 18:31

1 Answers1

1

One option could be:

df %>%
 mutate(Blinks_grp = with(rle(Blinks), rep(cumsum(values) * values, lengths)))

   Blinks Blinks_grp
1       0          0
2       0          0
3       1          1
4       1          1
5       1          1
6       0          0
7       0          0
8       1          2
9       1          2
10      1          2
11      1          2
12      0          0
13      0          0
14      1          3
15      1          3
tmfmnk
  • 38,881
  • 4
  • 47
  • 67