0

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
user438383
  • 5,716
  • 8
  • 28
  • 43
Luke Jenner
  • 129
  • 5
  • 2
    I think the canonical method would be to use `dplyr::cur_group_id`, as PaulS's (currently-deleted) answer shows. For instance, `df %>% group_by(grouping) %>% mutate(id = cur_group_id())` will give you your expected output. – r2evans Aug 02 '22 at 11:55

1 Answers1

1

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
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87