In a new variable row2
, how to repeat a sequential numbering (here a sequence from 3 to 6) by group of duplicated row1
values, which would start from a given value (here from row1
= 3), even if the last sequence is incomplete (here 3 to 5 for example)?
Thanks for help
Desired output:
> dat1
row1 row2
1 1 1
2 1 1
3 2 2
4 3 3 # start the sequence
5 4 4
6 4 4
7 4 4
8 5 5
9 5 5
10 6 6
11 6 6
12 6 6
13 7 3 # repeat the sequence
14 7 3
15 8 4
16 8 4
17 9 5
18 9 5
19 9 5
20 10 6
21 11 3 # and repeat again...
22 11 3
23 11 3
24 12 4
25 13 5
26 13 5 # ...even if incomplete
Initial data:
row1 <- c(1,1,2,
3,4,4,4,5,5,6,6,6,
7,7,8,8,9,9,9,10,
11,11,11,12,13,13)
dat1 <- data.frame(row1)
You could use if_else
to apply modulo
to val >=3
(row1 - 3) %% 4
cycles through 1,2,3, effectively mapping row1
values into 3,4,5,6 repeatedly.
+3
shifts the sequence to start at 3.
Values of row1 < 3
are kept untouched
dat1$row2 <- if_else(dat1$row1 >= 3, (dat1$row1 - 3) %% 4 + 3, dat1$row1)
row1 row2
1 1 1
2 1 1
3 2 2
4 3 3
5 4 4
6 4 4
7 4 4
8 5 5
9 5 5
10 6 6
11 6 6
12 6 6
13 7 3
14 7 3
15 8 4
16 8 4
17 9 5
18 9 5
19 9 5
20 10 6
21 11 3
22 11 3
23 11 3
24 12 4
25 13 5
26 13 5