Create a column based on "adjusted group_by" - R

Viewed 41

I have a dataframe with names of coaches of football clubs. Sometimes, after a while, the same coach returns to the team after being fired in the past. If I use a group_by, the output df would aggregate both coaches as a same group. However, I want that this create different groups. I do not know if I made myself clear, but I think this example would provide a better explanation than my text :D

If there is a package or other function that would do that, no problem!

Thanks in advance!

Example

library(dplyr)
df <- tibble(
  name = c("Jose","Jose", "Maria","Maria","Jose","Jose","Jose")
)
#Desired Output
adjusted_df <- tibble(
  name = c("Jose","Jose", "Maria","Maria","Jose","Jose","Jose"),
  number = c(1,1,1,1,2,2,2)
)
# I think after this desired output, I could group by name and number


1 Answers

This would give you unique ids if you group by name and id. It isn't the exact sequence you specified but this would work.

library(dplyr)
df <- tibble(
  name = c("Jose","Jose", "Maria","Maria","Jose","Jose","Jose")) |> 
  mutate(id = cumsum(ifelse(name != lag(name) | is.na(lag(name)), 1, 0)))
Related