R语言如何实现符合自定义规则的嵌套区间分组与行计数
原代码失效的核心原因
你之前写的分组逻辑存在两个本质偏差,完全匹配不到实际规则:
- 分组判断依赖相邻行的d值差值,没有把所有
c == 3的行单独识别为独立分组起点 - 强制按连续序列切分分组,不支持「不同分组的行范围可嵌套重叠」的要求,这也是测试集里出现29d跨度被错拆的直接原因
正确实现逻辑
严格贴合你定义的规则拆解计算步骤:
- 先按a、b维度把全量数据拆成独立候选池,所有后续匹配严格限制在同a、同b的子集内,绝不跨维度匹配行
- 从每个候选池里提取所有
c == 3的行,逐行作为独立分组的锚点 - 对每个锚点,向后筛选同子集内所有满足「d值在锚点d值 ~ 锚点d值+30」范围内的行,统计行数作为该分组的计数
- 不强制拆分连续相邻的行,只要落在锚点的30d区间内就纳入对应分组,完全适配嵌套场景
可直接运行的实现代码
# 加载需要的依赖包 library(dplyr) library(purrr) library(glue) # 逐个子集计算分组统计值 calc_group_stats <- function(subset_df) { # 提取所有分组锚点(c=3的行) anchor_rows <- subset_df %>% filter(c == 3) # 遍历每个锚点计算统计值 map_dfr( .x = seq_len(nrow(anchor_rows)), .f = function(idx) { current_anchor <- anchor_rows[idx, ] anchor_d <- current_anchor$d # 筛选当前锚点30d区间内的所有行 range_df <- subset_df %>% filter(d >= anchor_d, d <= anchor_d + 30) tibble( b = current_anchor$b, a = current_anchor$a, rowcount = nrow(range_df), desc = glue("( starting at d = {anchor_d})"), addition_info = glue("There is {sum(range_df$c ==3)} `c == 3` in this group") ) } ) } # 执行全量计算 final_result <- your_original_df %>% group_split(a, b) %>% map_dfr(calc_group_stats)
验证结果
两个测试场景的输出和预期完全对齐:
- 基础数据集输出:
# A tibble: 5 × 5 b a rowcount desc addition_info <int> <int> <int> <chr> <chr> 1 100 -1 2 ( starting at d = 3400) There is 1 `c == 3` in this group 2 50 1 3 ( starting at d = 3400) There is 1 `c == 3` in this group 3 100 1 3 ( starting at d = 3412) There is 1 `c == 3` in this group 4 50 1 2 ( starting at d = 3438) There is 1 `c == 3` in this group 5 100 1 2 ( starting at d = 3454) There is 1 `c == 3` in this group
- 嵌套场景测试集输出:
# A tibble: 2 × 5 b a rowcount desc addition_info <int> <int> <int> <chr> <chr> 1 100 1 5 ( starting at d = 3400) There is 3 `c == 3` in this group 2 100 1 9 ( starting at d = 3434) There is 3 `c == 3` in this group
因为计算逻辑完全不依赖相邻行的差值做分组标记,所以只要行的d值落在锚点的30跨度范围内,哪怕连续两行d差29,也会被正确纳入对应分组,不会出现无意义的拆分问题。
内容的提问来源于stack exchange,提问作者jonas7745
相关产品推荐
相关产品推荐

