r - 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
解决方案
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)
推荐阅读
- selenium - 使用页面工厂方法时如何解决selenium中的空指针异常
- row - DolphinDB 数据库中每一行的所有列的总和
- r - R中的配对观察
- dart - += Dart 中的运算符重载
- vhdl - VUnit 测试顺序组件
- xml - XML Schema 需要字符串或元素
- javascript - 动态 Chart.js 在调整大小时变为空白
- r - 使用 sqldf 在滞后窗口中准确加入 id 和最近日期
- android - 如果我使用 SymbolManager 来显示我的图标,如何在 android 的 mapbox 中添加聚类?
- google-cloud-ml - task.py:错误:无法识别的参数:使用 gcloud ai-platform 启动训练时 --job-dir