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

R语言按变量重置连续计数:SPC图控制限阶梯调整问题求助

Custom Streak Reset for SPC Chart Control Limit Adjustments

Hey there! Let's tackle this streak reset problem you're facing for your custom SPC chart. The core issue with your current code is that grouping by run doesn't correctly restart the consecutive count after hitting the 9th occurrence—instead of counting up from 1 again, it just stays at 1. Here's a reliable solution to get your desired runreset values:

Step-by-Step Solution

We'll use dplyr for data manipulation and runner for streak counting, with a custom grouping variable to reset the streak whenever we hit 9 consecutive values.

1. Initialize Example Data

First, let's set up your sample data in a tibble for clarity:

library(dplyr)
library(runner)

dat4 <- tibble(
  Dept = rep("A", 15),
  Count = c(F, T, T, T, T, T, T, T, T, T, T, T, F, F, T),
  run = c(1,1,2,3,4,5,6,7,8,9,10,11,1,2,1)
)

2. Create Reset Triggers and Groups

We'll add two helper variables:

  • reset_trigger: Flags the exact point where we need to reset the streak (when run == 9)
  • reset_group: Creates a new group every time a reset is triggered, so subsequent points are counted from 1 again
dat4 <- dat4 %>%
  group_by(Dept) %>%
  # Mark the 9th consecutive point as a reset trigger
  mutate(reset_trigger = ifelse(run == 9, 1, 0),
         # Build reset groups by accumulating triggers
         reset_group = cumsum(reset_trigger)) %>%
  # Recalculate streaks within each Dept and reset group
  group_by(Dept, reset_group) %>%
  mutate(runreset = streak_run(Count)) %>%
  ungroup()

3. Verify the Result

If you check dat4$runreset, you'll get exactly the output you expected:

dat4$runreset
# Output: 1 1 2 3 4 5 6 7 8 1 2 3 1 2 1

How This Works

  • The reset_trigger variable acts as a marker for when we need to start a new streak count.
  • reset_group uses cumsum() to create distinct blocks of data: every time a reset is triggered, all following points are placed into a new group.
  • By re-running streak_run() within each reset_group, we ensure that after the 9th consecutive point, the count starts over at 1 for the next set of matching values.

Next Steps for Control Limit Adjustment

Now that you have the correct runreset values, you can extend this logic to adjust your control limits:

  • For each Dept, check if runreset > 8
  • When this condition is met, recalculate the mean and control limits for that department, and apply the new limits to subsequent points

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:16:26