首页 > 解决方案 > Conditionally assign a value to column to say if it's before or after the value in another column

问题描述

Question:

I'd like to add another column called phase that is "preflop" before the first "flop" in the event column, then "postflop" between "flop" and "turn" etc.

Reproducible Example:

library(tibble)

df <- tibble(
event = c('action', 'action', 'Flop', 'action', 'action', 
          'Turn', 'action', 'action', 'River', 'action', 
          'action', 'Summary', 'action', 'action', 'Winner'),
hand = c("582129683", "582129683", "582129683", "582129683", "582129683", 
         "582129683", "582129683", "582129683", "582129683", "582129683",
         "582129683", "582129683", "582129683", "582129683", "582129683")
)

#> # A tibble: 15 x 2
#>    event   hand     
#>    <chr>   <chr>    
#>  1 action  582129683
#>  2 action  582129683
#>  3 Flop    582129683
#>  4 action  582129683
#>  5 action  582129683
#>  6 Turn    582129683
#>  7 action  582129683
#>  8 action  582129683
#>  9 River   582129683
#> 10 action  582129683
#> 11 action  582129683
#> 12 Summary 582129683
#> 13 action  582129683
#> 14 action  582129683
#> 15 Winner  582129683

标签: rdplyr

解决方案


Code to accomplish this:

library(tibble)
library(dplyr)
library(tidyr)

df %>% 
  group_by(hand) %>% 
  mutate(
    phase = case_when(
      event == "Flop" ~ "Flop",
      lead(event) == "Flop" ~ "Preflop",
      event == "Turn" ~ "Turn",
      lead(event) == "Turn" ~ "Flop",
      event == "River" ~ "River",
      lead(event) == "River" ~ "Turn",
      event == "Summary" ~ "Summary",
      lead(event) == "Summary" ~ "River",
      event == "Winner" ~ "Winner",
      lead(event) == "Winner" ~ "Summary"),
  ) %>% 
  fill(phase, .direction = "up") %>% 
  ungroup()

Output:

#> # A tibble: 15 x 3
#>    event   hand      phase  
#>    <chr>   <chr>     <chr>  
#>  1 action  582129683 Preflop
#>  2 action  582129683 Preflop
#>  3 Flop    582129683 Flop   
#>  4 action  582129683 Flop   
#>  5 action  582129683 Flop   
#>  6 Turn    582129683 Turn   
#>  7 action  582129683 Turn   
#>  8 action  582129683 Turn   
#>  9 River   582129683 River  
#> 10 action  582129683 River  
#> 11 action  582129683 River  
#> 12 Summary 582129683 Summary
#> 13 action  582129683 Summary
#> 14 action  582129683 Summary
#> 15 Winner  582129683 Winner

Created on 2021-01-31 by the reprex package (v0.3.0)


推荐阅读