Changing one column with specific rule in R
This is my df:
df_1 <- structure(list(col1 = c(0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0,
0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0)), class = c("tbl_df", "tbl",
"data.frame"), row.names = c(NA, -45L))
I want to create another column where values follow this order:
above row with value 2 will have value 1. Rows between 2 and 3 will have value 2, Rows between 3 and 4 will have value 3, Rows between 4 and 5 will have value 4, Rows between 5 and 6 will have value 5, Rows bellow 6 will have value 6.
In the end my col1 wil be:
col1 = c(1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3,
3, 3, 3, 3, 3,3, 3, 3, 3, 4, 4,4, 4, 4, 4, 4, 4, 4, 4, 5, 5,
5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6)
How can I do this? Is it possible do it with tidyverse packages?
df_1 %>%
mutate(col1 = cummax(replace(col1, col1 == 0, 1)))
col1
1 1
2 1
3 1
4 1
5 2
6 2
7 2
8 2
9 2
10 2
11 2
12 3
13 3
14 3
15 3
16 3
17 3
18 3
19 3
20 3
21 3
22 3
23 4
24 4
25 4
26 4
27 4
28 4
29 4
30 4
31 4
32 4
33 5
34 5
35 5
36 5
37 5
38 5
39 5
40 5
41 5
42 6
43 6
44 6
45 6