'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


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source