I have one column, A, that I need to use it to make a new column:

```
DT<- data.table(A = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3), B=0)
```

In a new column, B, I want to use a formula to separate every 1...9. So, the output will be like this:

```
A B
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
1 2
2 2
3 2
4 2
5 2
6 2
7 2
8 2
9 2
1 3
2 3
3 3
```

I did in Excel with the below formula: = IF(A2=1,IF(A1>1,B1+1,B1),B1

I tried this formula in R with different methods, shift(), lag(), ...:

```
DT$B = ifelse(DT$A == 1, ifelse(shift(DT$A, 1L, type="lag")>1,
DT$B<- 1+shift(DT$B, 1L, type="lag"),
DT$B<-shift(DT$B, 1L, type="lag")),
DT$B<-shift(DT$B, 1L, type="lag"))
```

The results for the above formula was:

```
A B
1: 1 NA
2: 2 NA
3: 3 NA
4: 4 1
5: 5 1
6: 6 1
7: 7 1
8: 8 1
9: 9 1
10: 1 1
11: 2 1
12: 3 1
13: 4 1
14: 5 1
15: 6 1
16: 7 1
17: 8 1
18: 9 1
19: 1 1
20: 2 1
21: 3 1
A B
```

I would appreciate if you could help me. Thanks, Milad