I'm working with data concerning different cases going through a proces consisting of different fases during a certain period in time. Each case has an unique id number. A proces can start in multiple fases and ends in fase "Finished" (except for still ungoing fases). A case can go through a proces multiple times. The data looks similar to this:
library(dplyr)
df1 <- structure(list(id = c("1", "1", "2", "2", "2", "2", "3", "3",
"3", "3", "3", "3", "3", "3", "3", "3"), time = structure(c(17453,
17458, 17453, 17462, 17727, 17735, 17453, 17484, 17568, 17665,
17665, 17709, 17727, 17727, 17757, 17819), class = "Date"), old_fase =
c(NA, "Fase 1", NA, "Fase 1", "Finished", "Fase 1", NA, "Fase 1", "Fase 2A",
"Finished", "Fase 2A", "Fase 2B", "Finished", "Fase 2B", "Fase 1",
"Fase 2A"), new_fase = c("Fase 1", "Finished", "Fase 1", "Finished",
"Fase 1", "Finished", "Fase 1", "Fase 2A", "Finished", "Fase 2A",
"Fase 2B", "Finished", "Fase 2B", "Fase 1", "Fase 2A", "Fase 2B"
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -16L))
For my analysis I want to create a new id based on the occurrence of each proces per id. Using group_by and mutate on "id" and "new_fase" creates the following incorrect solution. This happens because of the first occurrence of "Fase 2B" in row 11.
df1 %>%
group_by(id,new_fase) %>%
mutate(occurrence=row_number())
The correct solution should look like this:
df1 %>%
mutate(occurrence = c(rep(1, 4), 2, 2, rep(1, 3), rep(2, 3), rep(3, 4)))
I tried multiple approaches and read multiple Stackoverflow posts, but I am not able to figure it out correctly. Any help is appreciated, preferably using a tidyverse solution.