How to give numbers to each group of a dataframe with dplyr::group_by?

Viewed 6838

I want to give numbers to each group in a dataframe. For example, I have the following dataframe:

df = data.frame( from = c('a', 'a', 'b'), dest = c('b', 'c', 'd') )
#> df
    #from dest
#1    a    b
#2    a    c
#3    b    d

I want to group by from values and give a group number to each group. This is the expected result:

result = data.frame( from = c('a', 'a', 'b'), dest = c('b', 'c', 'd'), group_no = c(1,1,2) )
#> result
    #from dest group_no
#1    a    b        1
#2    a    c        1
#3    b    d        2

I can solve this problem using a for loop as follows:

groups = df$from %>% unique
i = 0
df$group_no = NA
for ( g in groups ) {
    i = i + 1
    df[ df$from == g, ]$group_no = i
}
#> df
    #from dest group_no
#1    a    b        1
#2    a    c        1
#3    b    d        2

I wonder if it is possible to solve this problem in a more elegant and functional way without using for loops? Specifically, I wonder if this can be done using dplyr::group_by function?

3 Answers
Related