Search code examples
rdataframecounter

R: Create a counter column that goes up every second row in a group


I would like to create a column where the counter goes up every second row (e.g., 1, 1, 2, 2, 3, 3), and have that counter be attached to the group name. This is an example of a dataframe that I have:

group numbering
g1         x
g1         y
g2         x
g2         y
g2         x
g2         y
g3         x
g3         y

The output would look something like this:

group numbering counter
g1         x      g1_1
g1         y      g1_1
g2         x      g2_1
g2         y      g2_1
g2         x      g2_2
g2         y      g2_2
g3         x      g3_1
g3         y      g3_1

Solution

  • Use group_by and row_number. This can be used irrespective of the size of the dataframe

    library(tidyverse)
    df %>%
      group_by(group, numbering) %>%
      mutate(counter = str_c(group, row_number(), sep='_'))
     group numbering counter
      <chr> <chr>     <chr>  
    1 g1    x         g1_1   
    2 g1    y         g1_1   
    3 g2    x         g2_1   
    4 g2    y         g2_1   
    5 g2    x         g2_2   
    6 g2    y         g2_2   
    7 g3    x         g3_1   
    8 g3    y         g3_1  
    

    in base R:

    transform(df, counter = ave(group, group, numbering, 
                                 FUN = \(x)paste(x, seq_along(x), sep='_')))
      group numbering counter
    1    g1         x    g1_1
    2    g1         y    g1_1
    3    g2         x    g2_1
    4    g2         y    g2_1
    5    g2         x    g2_2
    6    g2         y    g2_2
    7    g3         x    g3_1
    8    g3         y    g3_1