You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R滚动计数聚合:下一行含指定值时剔除当前行的实现问题

解决方案

核心逻辑是用dplyr内置的lead()函数提取当前行的下一行字段值,判断是否为"c"即可完成筛选:

完整可运行代码

library(tidyverse)

# 原始测试数据
data.frame(id = rep(123, 7),
           type = c(rep("d", 3), "c", rep("d", 3)),
           value = c(2, 4, 2, -2, 3, 5, 2)) %>% 
  group_by(id) %>% 
  # lead(type) 取同分组内下一行的type值,最后一行下一行无值默认返回NA
  mutate(next_type = lead(type),
         # 计入规则:当前行type不为c,且下一行type也不为c
         sum_field = ifelse(type != "c" & next_type != "c", value, NA)) %>% 
  summarise(current = sum(sum_field, na.rm = T),
            desired = sum(sum_field, na.rm = T))

结果说明

运行上述代码后汇总结果为14,符合预期:

  • 原第3行值为2的行,下一行type是"c",被排除不计入
  • 剩余计入的行对应value为2、4、3、5,求和正好为14

内容的提问来源于stack exchange,提问作者alexb523

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:27:03