Context: For each patient, return the most frequent Concessional_Status. If the frequency value is equal for a patient, use the first occurrence of Concessional_Status
I am unable to return the first occurrence of Concessional_Status if the frequency value is equal for a patient. I have tried @cderv solution which has a similar problem but I couldn't get the correct first occurrence : Replace values of a variable by the most frequent value
sample data:
sample <- tibble::tribble(
~Patient_ID, ~Concessional_Status,
1L, "G",
1L, "G",
1L, "B",
2L, "G",
2L, "B",
3L, "O",
3L, "B",
3L, "G",
4L, "X",
4L, "B"
)
My solution: Which is not correct
sample %>%
mutate(Concessional_Status = fct_inorder(Concessional_Status)) %>%
group_by_all() %>%
tally(sort = T) %>%
slice(1) %>%
ungroup() %>%
select(-n, Majority = Concessional_Status) %>%
left_join(sample, by=c("Patient_ID"="Patient_ID")) %>%
select(Patient_ID, Concessional_Status, everything())
Expected solution:
Expected_solution <- tibble::tribble(
~Patient_ID, ~Concessional_Status, ~Majority,
1L, "G", "G",
1L, "G", "G",
1L, "B", "G",
2L, "G", "G",
2L, "B", "G",
3L, "O", "O",
3L, "B", "O",
3L, "G", "O",
4L, "X", "X",
4L, "B", "G"
)
Any help would be greatly appreciated. Thanks