R语言按变量重置连续计数:SPC图控制限阶梯调整问题求助
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 (whenrun == 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_triggervariable acts as a marker for when we need to start a new streak count. reset_groupusescumsum()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 eachreset_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 ifrunreset > 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

