Search code examples
rdata-cleaningdata-wrangling

Add alternating string by group in R


I have a data frame formatted like so:

GameId
1
1
1
2
2
3
3
3

I want to create a new column called 'colour' which adds alternating rows with the colours white, black. I want this to reset for a new game Id and always begin with white so that it is formatted like so:

GameId colour
1 white
1 black
1 white
2 white
2 black
3 white
3 black
3 white

Thanks in advance for the help!


Solution

  • We could group by 'GameId' and create the 'colour' by replicating a vector of values and specifying the length.out as the group length (n())

    library(dplyr)
    df1 <- df1 %>%
        group_by(GameId) %>%
        mutate(colour = rep(c("white", "black"), length.out = n())) %>%
        ungroup
    

    -output

    df1
    # A tibble: 8 × 2
      GameId colour
       <int> <chr> 
    1      1 white 
    2      1 black 
    3      1 white 
    4      2 white 
    5      2 black 
    6      3 white 
    7      3 black 
    8      3 white 
    

    data

    df1 <- structure(list(GameId = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L)), 
    class = "data.frame", row.names = c(NA, 
    -8L))