Search code examples
rgroup-bydata-cleaningdata-wrangling

Adding Id number using group_by() in R


I have a data frame that's formatted like so:

evaluation grouping
1.00 a
0.50 a
2.00 b
1.00 b
2.00 b
0.50 c

I want to create a new column with ID numbers for each grouping like so:

evaluation grouping id
1.00 a 1
0.50 a 1
2.00 b 2
1.00 b 2
2.00 b 2
0.50 c 3

I have attempted this code:

data$id <- data %>% group_by(grouping) %>% 1:nrow(data) %>% ungroup

Solution

  • You can do this without group_by.

    df %>%
      mutate(ID = match(grouping, unique(grouping)))
    #>   evaluation grouping ID
    #> 1        1.0        a  1
    #> 2        0.5        a  1
    #> 3        2.0        b  2
    #> 4        1.0        b  2
    #> 5        2.0        b  2
    #> 6        0.5        c  3