如何使用R(优先tidyverse工具)统计玩家连续无中断得分回合次数
用tidyverse计算玩家对应对方连续未得分的次数
假设你的需求是:统计每个玩家对应的对手,连续出现得分0的回合数(即该玩家未被对方得分的连续次数),以下是基于tidyverse的实现方案:
1. 加载数据与依赖
首先加载tidyverse包,同时构造示例数据:
library(tidyverse) # 构造示例数据 df <- tibble( player = c("Bob", "Aaron", "Aaron", "Bob", "Aaron", "Aaron", "Bob", "Aaron", "Aaron", "Bob", "Bob", "Aaron"), runs = c(2, 1, 0, 4, 1, 0, 1, 0, 2, 3, 3, 2) )
2. 计算每个回合对应的对方连续未得分次数
通过标记对手、分组连续状态,计算每个回合对应的对方连续得0分的次数:
result <- df %>% # 标记当前玩家的对手 mutate(opponent = if_else(player == "Bob", "Aaron", "Bob")) %>% # 按对手分组,跟踪其得分状态的连续变化 group_by(opponent) %>% mutate( # 标记当前对手的得分是否为0 is_opponent_score_0 = runs == 0, # 生成连续相同状态的分组ID:状态变化时ID递增 streak_group = cumsum(is_opponent_score_0 != lag(is_opponent_score_0, default = !is_opponent_score_0[1])) ) %>% # 按对手和连续状态分组,计算每个连续段的长度 group_by(opponent, streak_group) %>% mutate( # 仅当对手得0分时,记录连续次数,否则为0 consecutive_opponent_0 = if_else(is_opponent_score_0, n(), 0) ) %>% ungroup() %>% # 保留核心列 select(player, runs, consecutive_opponent_0) # 查看结果 print(result)
输出结果:
# A tibble: 12 × 3 player runs consecutive_opponent_0 <chr> <dbl> <dbl> 1 Bob 2 0 2 Aaron 1 0 3 Aaron 0 1 4 Bob 4 0 5 Aaron 1 0 6 Aaron 0 1 7 Bob 1 0 8 Aaron 0 1 9 Aaron 2 0 10 Bob 3 0 11 Bob 3 0 12 Aaron 2 0
3. 统计每个玩家对应的对方连续未得分的最大次数
如果需要统计每个玩家对应的对手,连续未得分的最大次数,可以用以下代码:
max_streak_result <- df %>% mutate(opponent = if_else(player == "Bob", "Aaron", "Bob")) %>% group_by(opponent) %>% mutate( is_opponent_score_0 = runs == 0, streak_group = cumsum(is_opponent_score_0 != lag(is_opponent_score_0, default = !is_opponent_score_0[1])) ) %>% group_by(opponent, streak_group) %>% summarise( streak_length = n(), is_0 = first(is_opponent_score_0), .groups = "drop" ) %>% filter(is_0) %>% group_by(opponent) %>% summarise(max_consecutive_opponent_0 = max(streak_length, na.rm = TRUE)) %>% # 将对手列重命名为玩家列,明确对应关系 rename(player = opponent) # 查看结果 print(max_streak_result)
输出结果:
# A tibble: 2 × 2 player max_consecutive_opponent_0 <chr> <dbl> 1 Aaron 0 2 Bob 1
说明
- 核心逻辑是通过
cumsum()结合lag()生成连续状态的分组ID,实现纯tidyverse的连续次数计算 consecutive_opponent_0列表示当前回合对应的对手连续未得分的次数- 可以根据需求调整筛选条件,比如找出对手连续n次未得分的回合(添加
filter(consecutive_opponent_0 >= n))
内容的提问来源于stack exchange,提问作者codeweird
相关产品推荐
相关产品推荐

