Search code examples
rdplyrdata.tablesequential

Counter sequential of specific values in R


I have a column like that :

a = c(3, 1, 2, 3, 3, 3, 1, 3, 2, 3, 3, 1, 3, 2, 1, 3, 1)

I want to have a column that counts 1 and 2 sequentially to make a column like this:

   a b
1  3 0
2  1 1
3  2 2
4  3 2
5  3 2
6  3 2
7  1 3
8  3 3
9  2 4
10 3 4
11 3 4
12 1 5
13 3 5
14 2 6
15 1 7
16 3 7

Solution

  • We can use cumsum on a logical vector

    df1$b <- cumsum(df1$a %in% c(1, 2))
    

    data

    df1 <- data.frame(a)