1

I would like to create a column named day , based on every two shift one day up to 150 days .

shif  day
1   1    1
2   1    1
3   2    1
4   2    1
5   1    2
6   1    2
7   2    2
8   2    2
9   1    3
10  1    3
11  2    3
12  2    3
 

I was trying to this.

df_ <- data.frame(shift=rep(1:2,each=8,time=2))
x3 = df_ %>%
mutate(day = case_when(
  row_number() == 1 ~ 0,
  df_== lag(df_) ~ 1,
  TRUE ~ 2
))

but result is not successfull.

shift day
1      1  0
2      1  1
3      1  1
4      1  1
5      1  1
6      1  1
7      1  1
8      1  1
9      2  2
10     2  1
11     2  1
12     2  1
13     2  1
14     2  1
15     2  1
16     2  1
17     1  2
18     1  1
19     1  1
20     1  1
21     1  1
22     1  1
23     1  1
24     1  1
25     2  2
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
Malvis Va
  • 13
  • 4

2 Answers2

1

Groups of day start with the value 1, so create a binary variable telling where each group starts and then a cumsum trick makes of it a group number.

suppressPackageStartupMessages(
  library(dplyr)
)

df_ <- data.frame(shift=rep(1:2, each=2, time=3))

group_start <- 1L
df_ %>%
  mutate(
    day = shift == group_start & shift == lead(shift, default = group_start),
    day = cumsum(day)
  )
#>    shift day
#> 1      1   1
#> 2      1   1
#> 3      2   1
#> 4      2   1
#> 5      1   2
#> 6      1   2
#> 7      2   2
#> 8      2   2
#> 9      1   3
#> 10     1   3
#> 11     2   3
#> 12     2   3

Created on 2023-03-25 with reprex v2.0.2

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
1

If I understand correctly, this one should do it:

library(dplyr)
df %>% 
  mutate(day = as.integer(gl(n(), 4, n())))
 shif day
1     1   1
2     1   1
3     2   1
4     2   1
5     1   2
6     1   2
7     2   2
8     2   2
9     1   3
10    1   3
11    2   3
12    2   3
TarJae
  • 72,363
  • 6
  • 19
  • 66