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

使用dplyr按组筛选数据框:value全周一致时对n求和并过滤n=7的记录

dplyr 解决方案

核心逻辑

  • 按业务分组维度(本样本中为id+timeslot)分组
  • 校验分组是否符合要求:包含day1~day7的完整7条记录、组内所有value取值完全相同
  • 对符合要求的组求和n字段,再筛选求和结果等于7的记录

完整代码

# 加载依赖包
library(dplyr)

# 导入样本数据
df <- structure(list(id = c(1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3), day = c(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6), timeslot = c(1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3), value = c(110, 110, 110, 110, 110, 110, 110, 9990, 110, 110, 110, 110, 110, 9990, 110, 110, 110, 110, 8310, 110), n = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), row.names = c(NA, -20L), groups = structure(list(id = c(1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3), day = c(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6), timeslot = c(1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3), value = c(110, 110, 110, 110, 110, 110, 110, 9990, 110, 110, 110, 110, 110, 9990, 110, 110, 110, 110, 8310, 110), .rows = structure(list(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", "list"))), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", "tbl_df", "tbl", "data.frame"))

# 数据处理
result <- df %>%
  # 按分组维度分组,实际业务可自行调整字段
  group_by(id, timeslot) %>%
  # 汇总计算
  summarise(
    value = first(value),
    total_n = sum(n, na.rm = TRUE),
    # 校验组内value唯一且有完整7天数据
    is_qualified = n_distinct(value) == 1 & n() == 7,
    .groups = "drop"
  ) %>%
  # 筛选符合要求的记录
  filter(is_qualified, total_n == 7) %>%
  # 可选择去掉校验字段
  select(-is_qualified)

输出结果

运行上述代码后得到的结果和预期一致:

idtimeslotvaluetotal_n
111107

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:54:10