Fill cells dataframe based on multiple conditions

Solution 1:

If you use a method of reshaping to long format, splitting out the IDs based on the pattern of column names being variables made of letters and IDs being made of numbers, you can do the operation all at once in a couple lines and reshape back to wide. Using regex means you're not bound by either the number of players or the names of columns. I added an ID column for the games to differentiate rows; you could drop it afterward.

The reshaping itself is covered pretty extensively already (Reshaping multiple sets of measurement columns (wide format) into single columns (long format) for example) but is useful for problems that need to scale like this.

library(dplyr)

df %>%
  tibble::rowid_to_column(var = "game") %>%
  tidyr::pivot_longer(-game, names_to = c(".value", "num"), 
                      names_pattern = "(^[a-z]+)(\\d+$)") %>%
  mutate(flag = ifelse(player == 0 & lossallowed == "no", "FLAG", NA_character_)) %>%
  tidyr::pivot_wider(id_cols = game, names_from = num, values_from = player:flag, 
                     names_glue = "{.value}{num}")
#> # A tibble: 3 × 7
#>    game player001 player002 lossallowed001 lossallowed002 flag001 flag002
#>   <int>     <dbl>     <dbl> <chr>          <chr>          <chr>   <chr>  
#> 1     1         1         1 no             no             <NA>    <NA>   
#> 2     2         0         0 yes            no             <NA>    FLAG   
#> 3     3         3         5 no             yes            <NA>    <NA>