0

Say I have a df

df = data.frame(a = c('a', 'a','a','b','b','b'))
> df
  a
1 a
2 a
3 a
4 b
5 b
6 b

I want to code the same group of data to the same serial number.

I tried this:

df %>% group_by(a) %>% mutate(id = row_number())
# A tibble: 6 x 2
# Groups:   a [2]
  a        id
  <chr> <int>
1 a         1
2 a         2
3 a         3
4 b         1
5 b         2
6 b         3

But this is not I wanted. What I wanted is like this :

df_wanted = data.frame(a = c('a', 'a','a','b','b','b'),
                id = c(1,1,1,2,2,2))
df_wanted
  a id
1 a  1
2 a  1
3 a  1
4 b  2
5 b  2
6 b  2

Any help will be highly appreciated!

zhiwei li
  • 996
  • 4
  • 19

0 Answers0