Home > Blockchain >  Add alternating string by group in R
Add alternating string by group in R

Time:08-03

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!

CodePudding user response:

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))

CodePudding user response:

Using base R way

df$colour <- unlist(lapply(unique(df$GameId) ,\(x) rep(c("white", "black") ,
             length.out = sum(x == df$GameId))))
  • output
  GameId colour
1      1  white
2      1  black
3      1  white
4      2  white
5      2  black
6      3  white
7      3  black
8      3  white
  • Related