-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSPC.Rmd
3875 lines (2877 loc) · 173 KB
/
SPC.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Statistical Process Control in Healthcare"
author: "Sydney Paul, Dwight Barry, Brendan Bettinger, and Andrew Cooper"
date: "`r format(Sys.Date(), '%B %Y')`"
site: bookdown::bookdown_site
output: bookdown::html_book
documentclass: book
# output:
# bookdown::pdf_book:
# pandoc_args: ["--listings"]
classoption: openany
fontsize: 12pt
geometry: margin=1in
urlcolor: blue
linkcolor: blue
github-repo: sydneykpaul/spc_healthcare
description: "Using SPC methods in healthcare can be tricky. We show you how to do it correctly."
---
```{r include=FALSE, cache=FALSE}
library(dplyr)
library(tidyr)
plotSPC <- function(subgroup, point, mean, sigma, k = 3,
ucl.show = TRUE, lcl.show = TRUE,
band.show = TRUE, rule.show = TRUE,
ucl.max = Inf, lcl.min = -Inf,
label.x = "Subgroup", label.y = "Value") {
# Plots control chart with ggplot
##
# Args:
# subgroup: Subgroup definition (for x-axis)
# point: Subgroup sample values (for y-axis)
# mean: Process mean value (for center line)
# sigma: Process variation value (for control limits)
# k: Specification for k-sigma limits above and below center line, default is 3
# ucl.show: Visible upper control limit? Default is true
# lcl.show: Visible lower control limit? Default is true
# band.show: Visible bands between 1-2 sigma limits? Default is true
# rule.show: Highlight run rule indicators in orange? Default is true
# ucl.max: Maximum feasible value for upper control limit
# lcl.min: Minimum feasible value for lower control limit
# label.x: Specify x-axis label
# label.y: Specify y-axis label
df = data.frame(subgroup, point)
df$ucl = pmin(ucl.max, mean + k*sigma)
df$lcl = pmax(lcl.min, mean - k*sigma)
warn.points = function(rule, num, den) {
sets = mapply(seq, 1:(length(subgroup) - (den - 1)),
den:length(subgroup))
hits = apply(sets, 2, function(x) sum(rule[x])) >= num
intersect(c(sets[,hits]), which(rule))
}
orange.sigma = numeric()
p = ggplot(data = df, aes(x = subgroup)) +
geom_hline(yintercept = mean, col = "gray", size = 1)
if (ucl.show) {
p = p + geom_line(aes(y = ucl), col = "gray", size = 1)
}
if (lcl.show) {
p = p + geom_line(aes(y = lcl), col = "gray", size = 1)
}
if (band.show) {
p = p +
geom_ribbon(aes(ymin = mean + sigma,
ymax = mean + 2*sigma), alpha = 0.1) +
geom_ribbon(aes(ymin = pmax(lcl.min, mean - 2*sigma),
ymax = mean - sigma), alpha = 0.1)
orange.sigma = unique(c(
warn.points(point > mean + sigma, 4, 5),
warn.points(point < mean - sigma, 4, 5),
warn.points(point > mean + 2*sigma, 2, 3),
warn.points(point < mean - 2*sigma, 2, 3)
))
}
df$warn = "blue"
if (rule.show) {
shift.n = round(log(sum(point!=mean), 2) + 3)
orange = unique(c(orange.sigma,
warn.points(point > mean - sigma & point < mean + sigma, 15, 15),
warn.points(point > mean, shift.n, shift.n),
warn.points(point < mean, shift.n, shift.n)))
df$warn[orange] = "orange"
}
df$warn[point > df$ucl | point < df$lcl] = "red"
p +
geom_line(aes(y = point), col = "royalblue3") +
geom_point(data = df, aes(x = subgroup, y = point, col = warn)) +
scale_color_manual(values = c("blue" = "royalblue3", "orange" = "orangered", "red" = "red3"), guide = FALSE) +
labs(x = label.x, y = label.y) +
theme_bw()
}
############## Rachel's Data ##############
# Set seed for reproducibility
set.seed(2019)
# Generate fake infections data
dates <- strftime(seq(as.Date("2013/10/1"), by = "day", length.out = 730), "%Y-%m-01")
linedays <- sample(30:60,length(dates), replace = TRUE)
infections <- rpois(length(dates), 2/1000*linedays)
# Aggregate the data by month
infections <- aggregate(infections, by = list(dates), FUN = sum, na.rm = TRUE)$x
linedays <- aggregate(linedays, by = list(dates), FUN = sum, na.rm = TRUE)$x
months <- unique(dates)
# Create a tibble
rachel_data = tibble(months, infections, linedays)
############## example control charts ##############
# Set seed for reproducibility
set.seed(72)
############## u chart ##############
# Generate fake infections data
dates <- seq(as.Date("2013/10/1"), by = "day", length.out = 730)
linedays <- sample(30:60,length(dates), replace = TRUE)
infections <- rpois(length(dates), 2/1000*linedays)
# Aggregate the data by month
infections <- aggregate(infections, by = list(dates), FUN = sum, na.rm = TRUE)$x
linedays <- aggregate(linedays, by = list(dates), FUN = sum, na.rm = TRUE)$x
months <- unique(dates)
# Create a tibble
uchart_data <- tibble(months, infections, linedays)
############## p chart ##############
# Generate sample data
discharges <- sample(300:500, 24)
readmits <- rbinom(24, discharges, .2)
dates <- seq(as.Date("2013/10/1"), by = "month", length.out = 24)
# Create a tibble
pchart_data <- tibble(dates, readmits, discharges)
############## g chart ##############
# Generate fake data using u-chart example data
infections.index <- replace_na(which(infections > 0)[1:30], 0)
dfind <- data.frame(start = head(infections.index, length(infections.index) - 1) + 1,
end = tail(infections.index, length(infections.index) - 1))
linedays.btwn <- matrix(nrow = length(dfind$start))
for (i in 1:length(linedays.btwn)) {
sumover <- seq(dfind$start[i], dfind$end[i])
linedays.btwn[i] <- sum(linedays[sumover])
}
gchart_data <- dplyr::tibble(inf_index = 1:length(linedays.btwn), days_between = linedays.btwn)
############## IMR chart ##############
# Generate fake data
arrival <- cumsum(rexp(24, 1/10))
process <- rnorm(24, 5)
exit <- matrix(nrow = length(arrival))[,1]
exit[1] <- arrival[1] + process[1]
for (i in 1:length(arrival)) {
exit[i] <- max(arrival[i], exit[i - 1]) + process[i]
}
imrchart_data <- tibble(turnaround_time = exit - arrival, test_num = 1:length(exit))
############## XbarS chart ##############
# Generate fake patient wait times data
waits <- c(rnorm(1700, 30, 5), rnorm(650, 29.5, 5))
months <- strftime(sort(as.Date('2013-10-01') + sample(0:729, length(waits), TRUE)), "%Y-%m-01")
sample.n <- as.numeric(table(months))
xbarschart_data <- tibble(months, waits)
############## t chart ##############
# Generate sample data using g-chart example data
y <- linedays.btwn ^ (1/3.6)
mr <- matrix(nrow = length(y) - 1)
for (i in 1:length(y) - 1) {
mr[i] <- abs(y[i + 1] - y[i])
}
mr <- mr[mr <= 3.27 * mean(mr)]
tchart_data <- tibble(inf_index = 1:length(y), days_between = y)
############## change in process example ##############
# Create fake data with change in process at 28 months
intervention = data.frame(date = seq(as.Date("2006-01-01"), by = 'month', length.out = 48),
y = c(rpois(28, 6), rpois(20, 3)),
n = round(rnorm(48, 450, 50)))
```
```{r setup, include=FALSE}
# Global options
knitr::opts_chunk$set(warning = FALSE, message = FALSE, comment = NA, highlight = TRUE, fig.height = 3.5)
# options("width" = 54)
knitr::opts_chunk$set(fig.pos = 'H')
# Load libraries
library(dplyr)
library(scales)
library(lubridate)
library(forecast)
library(ggseas)
library(qicharts2)
library(bookdown)
library(knitr)
library(ggplot2)
library(ggExtra)
library(gridExtra)
library(pander)
```
# Preface {-}
## We have a problem {#preface_problem}
Statistical process control (SPC) was a triumph of manufacturing analytics, and its success spread across a variety of industries---most improbably, into healthcare.
Healthcare is rarely compatible with the idea of an assembly line, but lean manufacturing thinking ("Lean") has taken over healthcare management around the world, and SPC methods are common tools in Lean.
Unlike in manufacturing, stability is an inherently tricky concept in healthcare, so this has led to much *misuse* of these methods. Bad methods lead to bad inferences, and bad inferences can lead to poor decisions.
This book aims to help analysts apply SPC methods more accurately in healthcare, using the statistical software R.
## Common questions {#preface_questions}
### _Who is this book for?_ {-}
This book is geared toward analysts working in the healthcare industry, who are already familiar with basic SPC methods and concepts. We do cover some basics, but we focus primarily on the areas that cause the most misunderstandings and misuse; The section [Useful References](#useful_resources) in the Additional Resources chapter provides a great place to start or continue learning about SPC.
### _What do I need to start?_ {-}
OVERVIEW AND LINK TO SHINY APP.
## About {#preface_about}
### _Who are we?_ {-}
We are all analysts at *Seattle Children's Hospital* in Seattle, Washington, USA.
* Sydney Paul is a Data Science Intern in *Enterprise Analytics*.
* Dwight Barry is a Principal Data Scientist in *Enterprise Analytics*. Twitter: \@healthstatsdude
* Brendan Bettinger is a Senior Analyst in *Infection Prevention*.
* Andy Cooper is a Principal Data Scientist in *Enterprise Analytics*. Twitter: \@DataSciABC
### _What if I find a typo?_ {-}
You can submit pull requests for any errors or typos at https://github.com/sydneykpaul/spc_healthcare_with_r.
<!--chapter:end:index.Rmd-->
---
title: "01_TutorialLoadFile"
output:
html_document:
df_print: paged
---
```{r include=FALSE, cache=FALSE}
library(dplyr)
library(tidyr)
plotSPC <- function(subgroup, point, mean, sigma, k = 3,
ucl.show = TRUE, lcl.show = TRUE,
band.show = TRUE, rule.show = TRUE,
ucl.max = Inf, lcl.min = -Inf,
label.x = "Subgroup", label.y = "Value") {
# Plots control chart with ggplot
##
# Args:
# subgroup: Subgroup definition (for x-axis)
# point: Subgroup sample values (for y-axis)
# mean: Process mean value (for center line)
# sigma: Process variation value (for control limits)
# k: Specification for k-sigma limits above and below center line, default is 3
# ucl.show: Visible upper control limit? Default is true
# lcl.show: Visible lower control limit? Default is true
# band.show: Visible bands between 1-2 sigma limits? Default is true
# rule.show: Highlight run rule indicators in orange? Default is true
# ucl.max: Maximum feasible value for upper control limit
# lcl.min: Minimum feasible value for lower control limit
# label.x: Specify x-axis label
# label.y: Specify y-axis label
df = data.frame(subgroup, point)
df$ucl = pmin(ucl.max, mean + k*sigma)
df$lcl = pmax(lcl.min, mean - k*sigma)
warn.points = function(rule, num, den) {
sets = mapply(seq, 1:(length(subgroup) - (den - 1)),
den:length(subgroup))
hits = apply(sets, 2, function(x) sum(rule[x])) >= num
intersect(c(sets[,hits]), which(rule))
}
orange.sigma = numeric()
p = ggplot(data = df, aes(x = subgroup)) +
geom_hline(yintercept = mean, col = "gray", size = 1)
if (ucl.show) {
p = p + geom_line(aes(y = ucl), col = "gray", size = 1)
}
if (lcl.show) {
p = p + geom_line(aes(y = lcl), col = "gray", size = 1)
}
if (band.show) {
p = p +
geom_ribbon(aes(ymin = mean + sigma,
ymax = mean + 2*sigma), alpha = 0.1) +
geom_ribbon(aes(ymin = pmax(lcl.min, mean - 2*sigma),
ymax = mean - sigma), alpha = 0.1)
orange.sigma = unique(c(
warn.points(point > mean + sigma, 4, 5),
warn.points(point < mean - sigma, 4, 5),
warn.points(point > mean + 2*sigma, 2, 3),
warn.points(point < mean - 2*sigma, 2, 3)
))
}
df$warn = "blue"
if (rule.show) {
shift.n = round(log(sum(point!=mean), 2) + 3)
orange = unique(c(orange.sigma,
warn.points(point > mean - sigma & point < mean + sigma, 15, 15),
warn.points(point > mean, shift.n, shift.n),
warn.points(point < mean, shift.n, shift.n)))
df$warn[orange] = "orange"
}
df$warn[point > df$ucl | point < df$lcl] = "red"
p +
geom_line(aes(y = point), col = "royalblue3") +
geom_point(data = df, aes(x = subgroup, y = point, col = warn)) +
scale_color_manual(values = c("blue" = "royalblue3", "orange" = "orangered", "red" = "red3"), guide = FALSE) +
labs(x = label.x, y = label.y) +
theme_bw()
}
############## Rachel's Data ##############
# Set seed for reproducibility
set.seed(2019)
# Generate fake infections data
dates <- strftime(seq(as.Date("2013/10/1"), by = "day", length.out = 730), "%Y-%m-01")
linedays <- sample(30:60,length(dates), replace = TRUE)
infections <- rpois(length(dates), 2/1000*linedays)
# Aggregate the data by month
infections <- aggregate(infections, by = list(dates), FUN = sum, na.rm = TRUE)$x
linedays <- aggregate(linedays, by = list(dates), FUN = sum, na.rm = TRUE)$x
months <- unique(dates)
# Create a tibble
rachel_data = tibble(months, infections, linedays)
############## example control charts ##############
# Set seed for reproducibility
set.seed(72)
############## u chart ##############
# Generate fake infections data
dates <- seq(as.Date("2013/10/1"), by = "day", length.out = 730)
linedays <- sample(30:60,length(dates), replace = TRUE)
infections <- rpois(length(dates), 2/1000*linedays)
# Aggregate the data by month
infections <- aggregate(infections, by = list(dates), FUN = sum, na.rm = TRUE)$x
linedays <- aggregate(linedays, by = list(dates), FUN = sum, na.rm = TRUE)$x
months <- unique(dates)
# Create a tibble
uchart_data <- tibble(months, infections, linedays)
############## p chart ##############
# Generate sample data
discharges <- sample(300:500, 24)
readmits <- rbinom(24, discharges, .2)
dates <- seq(as.Date("2013/10/1"), by = "month", length.out = 24)
# Create a tibble
pchart_data <- tibble(dates, readmits, discharges)
############## g chart ##############
# Generate fake data using u-chart example data
infections.index <- replace_na(which(infections > 0)[1:30], 0)
dfind <- data.frame(start = head(infections.index, length(infections.index) - 1) + 1,
end = tail(infections.index, length(infections.index) - 1))
linedays.btwn <- matrix(nrow = length(dfind$start))
for (i in 1:length(linedays.btwn)) {
sumover <- seq(dfind$start[i], dfind$end[i])
linedays.btwn[i] <- sum(linedays[sumover])
}
gchart_data <- dplyr::tibble(inf_index = 1:length(linedays.btwn), days_between = linedays.btwn)
############## IMR chart ##############
# Generate fake data
arrival <- cumsum(rexp(24, 1/10))
process <- rnorm(24, 5)
exit <- matrix(nrow = length(arrival))[,1]
exit[1] <- arrival[1] + process[1]
for (i in 1:length(arrival)) {
exit[i] <- max(arrival[i], exit[i - 1]) + process[i]
}
imrchart_data <- tibble(turnaround_time = exit - arrival, test_num = 1:length(exit))
############## XbarS chart ##############
# Generate fake patient wait times data
waits <- c(rnorm(1700, 30, 5), rnorm(650, 29.5, 5))
months <- strftime(sort(as.Date('2013-10-01') + sample(0:729, length(waits), TRUE)), "%Y-%m-01")
sample.n <- as.numeric(table(months))
xbarschart_data <- tibble(months, waits)
############## t chart ##############
# Generate sample data using g-chart example data
y <- linedays.btwn ^ (1/3.6)
mr <- matrix(nrow = length(y) - 1)
for (i in 1:length(y) - 1) {
mr[i] <- abs(y[i + 1] - y[i])
}
mr <- mr[mr <= 3.27 * mean(mr)]
tchart_data <- tibble(inf_index = 1:length(y), days_between = y)
############## change in process example ##############
# Create fake data with change in process at 28 months
intervention = data.frame(date = seq(as.Date("2006-01-01"), by = 'month', length.out = 48),
y = c(rpois(28, 6), rpois(20, 3)),
n = round(rnorm(48, 450, 50)))
```
# Step 1: Load your file {-}
Over the next few chapters we will walk you through using the accompanying SPC R shiny application to create SPC charts. The first step is to load your data. When you first launch the application, you are greeted with the following screen.
```{r echo=FALSE, fig.align='center', fig.cap="The landing page of the SPC Shiny App"}
knitr::include_graphics("step1_load_file.png")
```
On the left-side panel there are several options for customizing your file import. The first is the file type. Valid file types are `.xlsx`, `.xls`, `.csv`, or `.txt`, just select the corresponding radio button. Next, you can specify whether your file contains a header or not, i.e. column names. Finally, there are two options for customizing a `.csv` or `.txt` import: separator and quote. Just as CSV stands for comma-separated values, there are other commonly used separators like semicolon or tab. The quote option tells the application how to handle quotes in the data using a single character.
Once you have set your desired options, you may click the `Browse` button to find your file. You can select a single file and click "Open" like any file dialog box. If your data has been divided across several files, you may hold the "Ctrl" button and select them all. This will stack the files on top of each other, so ensure that the column names are identical if using this method.
Once you have loaded your data, a preview will appear on the right half of the application. You may filter by column or use the Previous and Next buttons to search through the data. Once you are comfortable that it has loaded the data correctly, you may hit the "Continue" button to move to the next step.
In this tutorial we will use a simulated CLABSI (central line associated blood stream infection) dataset. The following image is the application after loading this dataset.
```{r echo=FALSE, fig.align='center', fig.cap="Data has been successfully loaded into SPC Shiny App"}
knitr::include_graphics("step1_successfully_loaded.png")
```
Next, we will walk you through exploring your data.
<!--chapter:end:01_Tutorial_LoadFile.Rmd-->
---
title: "02_TutorialParameters"
output: pdf_document
---
```{r include=FALSE, cache=FALSE}
library(dplyr)
library(tidyr)
plotSPC <- function(subgroup, point, mean, sigma, k = 3,
ucl.show = TRUE, lcl.show = TRUE,
band.show = TRUE, rule.show = TRUE,
ucl.max = Inf, lcl.min = -Inf,
label.x = "Subgroup", label.y = "Value") {
# Plots control chart with ggplot
##
# Args:
# subgroup: Subgroup definition (for x-axis)
# point: Subgroup sample values (for y-axis)
# mean: Process mean value (for center line)
# sigma: Process variation value (for control limits)
# k: Specification for k-sigma limits above and below center line, default is 3
# ucl.show: Visible upper control limit? Default is true
# lcl.show: Visible lower control limit? Default is true
# band.show: Visible bands between 1-2 sigma limits? Default is true
# rule.show: Highlight run rule indicators in orange? Default is true
# ucl.max: Maximum feasible value for upper control limit
# lcl.min: Minimum feasible value for lower control limit
# label.x: Specify x-axis label
# label.y: Specify y-axis label
df = data.frame(subgroup, point)
df$ucl = pmin(ucl.max, mean + k*sigma)
df$lcl = pmax(lcl.min, mean - k*sigma)
warn.points = function(rule, num, den) {
sets = mapply(seq, 1:(length(subgroup) - (den - 1)),
den:length(subgroup))
hits = apply(sets, 2, function(x) sum(rule[x])) >= num
intersect(c(sets[,hits]), which(rule))
}
orange.sigma = numeric()
p = ggplot(data = df, aes(x = subgroup)) +
geom_hline(yintercept = mean, col = "gray", size = 1)
if (ucl.show) {
p = p + geom_line(aes(y = ucl), col = "gray", size = 1)
}
if (lcl.show) {
p = p + geom_line(aes(y = lcl), col = "gray", size = 1)
}
if (band.show) {
p = p +
geom_ribbon(aes(ymin = mean + sigma,
ymax = mean + 2*sigma), alpha = 0.1) +
geom_ribbon(aes(ymin = pmax(lcl.min, mean - 2*sigma),
ymax = mean - sigma), alpha = 0.1)
orange.sigma = unique(c(
warn.points(point > mean + sigma, 4, 5),
warn.points(point < mean - sigma, 4, 5),
warn.points(point > mean + 2*sigma, 2, 3),
warn.points(point < mean - 2*sigma, 2, 3)
))
}
df$warn = "blue"
if (rule.show) {
shift.n = round(log(sum(point!=mean), 2) + 3)
orange = unique(c(orange.sigma,
warn.points(point > mean - sigma & point < mean + sigma, 15, 15),
warn.points(point > mean, shift.n, shift.n),
warn.points(point < mean, shift.n, shift.n)))
df$warn[orange] = "orange"
}
df$warn[point > df$ucl | point < df$lcl] = "red"
p +
geom_line(aes(y = point), col = "royalblue3") +
geom_point(data = df, aes(x = subgroup, y = point, col = warn)) +
scale_color_manual(values = c("blue" = "royalblue3", "orange" = "orangered", "red" = "red3"), guide = FALSE) +
labs(x = label.x, y = label.y) +
theme_bw()
}
############## Rachel's Data ##############
# Set seed for reproducibility
set.seed(2019)
# Generate fake infections data
dates <- strftime(seq(as.Date("2013/10/1"), by = "day", length.out = 730), "%Y-%m-01")
linedays <- sample(30:60,length(dates), replace = TRUE)
infections <- rpois(length(dates), 2/1000*linedays)
# Aggregate the data by month
infections <- aggregate(infections, by = list(dates), FUN = sum, na.rm = TRUE)$x
linedays <- aggregate(linedays, by = list(dates), FUN = sum, na.rm = TRUE)$x
months <- unique(dates)
# Create a tibble
rachel_data = tibble(months, infections, linedays)
############## example control charts ##############
# Set seed for reproducibility
set.seed(72)
############## u chart ##############
# Generate fake infections data
dates <- seq(as.Date("2013/10/1"), by = "day", length.out = 730)
linedays <- sample(30:60,length(dates), replace = TRUE)
infections <- rpois(length(dates), 2/1000*linedays)
# Aggregate the data by month
infections <- aggregate(infections, by = list(dates), FUN = sum, na.rm = TRUE)$x
linedays <- aggregate(linedays, by = list(dates), FUN = sum, na.rm = TRUE)$x
months <- unique(dates)
# Create a tibble
uchart_data <- tibble(months, infections, linedays)
############## p chart ##############
# Generate sample data
discharges <- sample(300:500, 24)
readmits <- rbinom(24, discharges, .2)
dates <- seq(as.Date("2013/10/1"), by = "month", length.out = 24)
# Create a tibble
pchart_data <- tibble(dates, readmits, discharges)
############## g chart ##############
# Generate fake data using u-chart example data
infections.index <- replace_na(which(infections > 0)[1:30], 0)
dfind <- data.frame(start = head(infections.index, length(infections.index) - 1) + 1,
end = tail(infections.index, length(infections.index) - 1))
linedays.btwn <- matrix(nrow = length(dfind$start))
for (i in 1:length(linedays.btwn)) {
sumover <- seq(dfind$start[i], dfind$end[i])
linedays.btwn[i] <- sum(linedays[sumover])
}
gchart_data <- dplyr::tibble(inf_index = 1:length(linedays.btwn), days_between = linedays.btwn)
############## IMR chart ##############
# Generate fake data
arrival <- cumsum(rexp(24, 1/10))
process <- rnorm(24, 5)
exit <- matrix(nrow = length(arrival))[,1]
exit[1] <- arrival[1] + process[1]
for (i in 1:length(arrival)) {
exit[i] <- max(arrival[i], exit[i - 1]) + process[i]
}
imrchart_data <- tibble(turnaround_time = exit - arrival, test_num = 1:length(exit))
############## XbarS chart ##############
# Generate fake patient wait times data
waits <- c(rnorm(1700, 30, 5), rnorm(650, 29.5, 5))
months <- strftime(sort(as.Date('2013-10-01') + sample(0:729, length(waits), TRUE)), "%Y-%m-01")
sample.n <- as.numeric(table(months))
xbarschart_data <- tibble(months, waits)
############## t chart ##############
# Generate sample data using g-chart example data
y <- linedays.btwn ^ (1/3.6)
mr <- matrix(nrow = length(y) - 1)
for (i in 1:length(y) - 1) {
mr[i] <- abs(y[i + 1] - y[i])
}
mr <- mr[mr <= 3.27 * mean(mr)]
tchart_data <- tibble(inf_index = 1:length(y), days_between = y)
############## change in process example ##############
# Create fake data with change in process at 28 months
intervention = data.frame(date = seq(as.Date("2006-01-01"), by = 'month', length.out = 48),
y = c(rpois(28, 6), rpois(20, 3)),
n = round(rnorm(48, 450, 50)))
```
# Step 2: Set your parameters {#parameters}
The next step allows you to set your desired parameters for creating your SPC charts. The tab should look like the following:
```{r echo=FALSE, fig.align='center', fig.cap="Application page to set your parameters"}
knitr::include_graphics("step2_set_parameters.png")
```
The left-side panel contains all the options you will need. The first is the desired multiplier. In a hospital context, this is often "per how many patient days". The default option is 1000, so make sure to select 1 if you do not wish to have a multiplier.
The next three drop down menus are populated with the column names of your data. You must match the desired column with its desired purpose. For SPC charts you have a a date column or subgroups (values to plot along the x-axis), and a value column (measures or counts to plot along the y-axis). In some cases you may have a column of subgroup sizes. If this is not applicable to your use-case, then simple leave the "Denominator (subgroup sizes)" as "SELECT" and it will not be used.
The final option on the left-side panel is a check box that says "Check this box if you want to compare your data based on a qualitative grouping column, ex. departments". If this is applicable to your data, you may check this box. This will create another drop-down box populated with your data's column's names. Select the column that you wish to compare across like you did in the previous drop-down menus.
We have set the following parameters for our example CLABSI data:
```{r echo=FALSE, fig.align='center', fig.cap="Parameters are set for example CLABSI data"}
knitr::include_graphics("step2_successfully_set_parameters.png")
```
We want to use 1000 for our multiplier so that the data is represented in per 1000 patient days. For the date (x-axis) we will use the column named "date". For the numerator (y-axis) we will use the counts of CLABSI events in the column named "clabsi_count". For CLABSI events, we do have subgroup size data. So, for the denominator drop-down we select the column named "central_line_days".
Finally, we have decided that we want to compare the CLABSI rates across departments. We have a single column named "department" which contains the department where the CLABSI events occurred.
After you are satisfied with your parameters, you may click the "Continue" button to proceed with the analysis.
<!--chapter:end:02_Tutorial_Parameters.Rmd-->
---
title: "03_Tutorial_EDA_Assumptions"
output: pdf_document
---
```{r include=FALSE, cache=FALSE}
library(dplyr)
library(tidyr)
plotSPC <- function(subgroup, point, mean, sigma, k = 3,
ucl.show = TRUE, lcl.show = TRUE,
band.show = TRUE, rule.show = TRUE,
ucl.max = Inf, lcl.min = -Inf,
label.x = "Subgroup", label.y = "Value") {
# Plots control chart with ggplot
##
# Args:
# subgroup: Subgroup definition (for x-axis)
# point: Subgroup sample values (for y-axis)
# mean: Process mean value (for center line)
# sigma: Process variation value (for control limits)
# k: Specification for k-sigma limits above and below center line, default is 3
# ucl.show: Visible upper control limit? Default is true
# lcl.show: Visible lower control limit? Default is true
# band.show: Visible bands between 1-2 sigma limits? Default is true
# rule.show: Highlight run rule indicators in orange? Default is true
# ucl.max: Maximum feasible value for upper control limit
# lcl.min: Minimum feasible value for lower control limit
# label.x: Specify x-axis label
# label.y: Specify y-axis label
df = data.frame(subgroup, point)
df$ucl = pmin(ucl.max, mean + k*sigma)
df$lcl = pmax(lcl.min, mean - k*sigma)
warn.points = function(rule, num, den) {
sets = mapply(seq, 1:(length(subgroup) - (den - 1)),
den:length(subgroup))
hits = apply(sets, 2, function(x) sum(rule[x])) >= num
intersect(c(sets[,hits]), which(rule))
}
orange.sigma = numeric()
p = ggplot(data = df, aes(x = subgroup)) +
geom_hline(yintercept = mean, col = "gray", size = 1)
if (ucl.show) {
p = p + geom_line(aes(y = ucl), col = "gray", size = 1)
}
if (lcl.show) {
p = p + geom_line(aes(y = lcl), col = "gray", size = 1)
}
if (band.show) {
p = p +
geom_ribbon(aes(ymin = mean + sigma,
ymax = mean + 2*sigma), alpha = 0.1) +
geom_ribbon(aes(ymin = pmax(lcl.min, mean - 2*sigma),
ymax = mean - sigma), alpha = 0.1)
orange.sigma = unique(c(
warn.points(point > mean + sigma, 4, 5),
warn.points(point < mean - sigma, 4, 5),
warn.points(point > mean + 2*sigma, 2, 3),
warn.points(point < mean - 2*sigma, 2, 3)
))
}
df$warn = "blue"
if (rule.show) {
shift.n = round(log(sum(point!=mean), 2) + 3)
orange = unique(c(orange.sigma,
warn.points(point > mean - sigma & point < mean + sigma, 15, 15),
warn.points(point > mean, shift.n, shift.n),
warn.points(point < mean, shift.n, shift.n)))
df$warn[orange] = "orange"
}
df$warn[point > df$ucl | point < df$lcl] = "red"
p +
geom_line(aes(y = point), col = "royalblue3") +
geom_point(data = df, aes(x = subgroup, y = point, col = warn)) +
scale_color_manual(values = c("blue" = "royalblue3", "orange" = "orangered", "red" = "red3"), guide = FALSE) +
labs(x = label.x, y = label.y) +
theme_bw()
}
############## Rachel's Data ##############
# Set seed for reproducibility
set.seed(2019)
# Generate fake infections data
dates <- strftime(seq(as.Date("2013/10/1"), by = "day", length.out = 730), "%Y-%m-01")
linedays <- sample(30:60,length(dates), replace = TRUE)
infections <- rpois(length(dates), 2/1000*linedays)
# Aggregate the data by month
infections <- aggregate(infections, by = list(dates), FUN = sum, na.rm = TRUE)$x
linedays <- aggregate(linedays, by = list(dates), FUN = sum, na.rm = TRUE)$x
months <- unique(dates)
# Create a tibble
rachel_data = tibble(months, infections, linedays)
############## example control charts ##############
# Set seed for reproducibility
set.seed(72)
############## u chart ##############
# Generate fake infections data
dates <- seq(as.Date("2013/10/1"), by = "day", length.out = 730)
linedays <- sample(30:60,length(dates), replace = TRUE)
infections <- rpois(length(dates), 2/1000*linedays)
# Aggregate the data by month
infections <- aggregate(infections, by = list(dates), FUN = sum, na.rm = TRUE)$x
linedays <- aggregate(linedays, by = list(dates), FUN = sum, na.rm = TRUE)$x
months <- unique(dates)
# Create a tibble
uchart_data <- tibble(months, infections, linedays)
############## p chart ##############
# Generate sample data
discharges <- sample(300:500, 24)
readmits <- rbinom(24, discharges, .2)
dates <- seq(as.Date("2013/10/1"), by = "month", length.out = 24)
# Create a tibble
pchart_data <- tibble(dates, readmits, discharges)
############## g chart ##############
# Generate fake data using u-chart example data
infections.index <- replace_na(which(infections > 0)[1:30], 0)
dfind <- data.frame(start = head(infections.index, length(infections.index) - 1) + 1,
end = tail(infections.index, length(infections.index) - 1))
linedays.btwn <- matrix(nrow = length(dfind$start))
for (i in 1:length(linedays.btwn)) {
sumover <- seq(dfind$start[i], dfind$end[i])
linedays.btwn[i] <- sum(linedays[sumover])
}
gchart_data <- dplyr::tibble(inf_index = 1:length(linedays.btwn), days_between = linedays.btwn)
############## IMR chart ##############
# Generate fake data
arrival <- cumsum(rexp(24, 1/10))
process <- rnorm(24, 5)
exit <- matrix(nrow = length(arrival))[,1]
exit[1] <- arrival[1] + process[1]
for (i in 1:length(arrival)) {
exit[i] <- max(arrival[i], exit[i - 1]) + process[i]
}
imrchart_data <- tibble(turnaround_time = exit - arrival, test_num = 1:length(exit))
############## XbarS chart ##############
# Generate fake patient wait times data
waits <- c(rnorm(1700, 30, 5), rnorm(650, 29.5, 5))
months <- strftime(sort(as.Date('2013-10-01') + sample(0:729, length(waits), TRUE)), "%Y-%m-01")
sample.n <- as.numeric(table(months))
xbarschart_data <- tibble(months, waits)
############## t chart ##############
# Generate sample data using g-chart example data
y <- linedays.btwn ^ (1/3.6)
mr <- matrix(nrow = length(y) - 1)
for (i in 1:length(y) - 1) {
mr[i] <- abs(y[i + 1] - y[i])
}
mr <- mr[mr <= 3.27 * mean(mr)]
tchart_data <- tibble(inf_index = 1:length(y), days_between = y)
############## change in process example ##############
# Create fake data with change in process at 28 months
intervention = data.frame(date = seq(as.Date("2006-01-01"), by = 'month', length.out = 48),
y = c(rpois(28, 6), rpois(20, 3)),
n = round(rnorm(48, 450, 50)))
```
# Step 2: Exploratory Data Analysis and Checking Assumptions {#eda_assumptions}
## Exploratory Data Analysis
It is important to understand your data. Your data is the foundation for all further analysis. You cannot create any meaningful interpretation from bad data, and not all data is suited for SPC charts. There are many tools for data exploration, and you get to decide how deep to explore. Before you start blindly exploring, its important to think about your data.
Take a minute to answer the following questions:
1. What are the typical values of your data, i.e. what do you expect the range of the data to be? 2. What do you think the distribution will look like? Will it be skewed? Will there be a lot of variance?
This tab of the application contains a lot of important information. We have broken this information into four easily digestible sections. There will be a control or important text on the left-side panel, with a corresponding graph on the right-side panel.
<br>
The first section is the area highlighted in blue. The blue section shows a plot your data as a line chart and a histogram (adding a density overlay provides a more "objective" sense of the distribution).
```{r echo=FALSE, fig.align='center', fig.cap="Exploring the distributions of your data"}
knitr::include_graphics("step3_distributions.png")
```
In these plots, consider:
1. The shape of the distribution: symmetrical/skewed, uniform/peaked/multimodal, whether changes in binwidth show patterning, etc.
2. Whether you see any trending, cycles, or suggestions of autocorrelation (we will discuss this more in the next step).
3. Whether there are any obvious outliers or inliers---basically, any points deviating from the expected pattern.
The black points and line are simply the number of infections plotted over time. The blue line is the trend line, and the shaded grey area is the confidence interval of the trend line. We can say with 95% confidence that the true, *actual* trend line falls within this grey area. The grey area is *not* a control limit. Remember this is a line chart, not a SPC chart.
A histogram is an excellent tool for examining the distribution of the data. In R, there are two key arguments that you need to change to explore your data: `binwidth` **_or_** `bins`. You can control either by using the slider on the left-side panel. The default slider is controlling the number of bins, but you can select the check box to control the binwidth instead. This parameter is completely user dependent. It is up to you to change this parameter until *you* think you have a good understanding of the distribution.
Notice for our CLABSI example we have two line plots and two histograms. This is because we are comparing across departments of which we only have two, Acute Care and Critical Care. If we had four departments, we would have four of each graph. If you are not comparing across a column, then you should see only one line graph and one histogram.
Now we will refer back to the questions for evaluating are example plots.
```{r echo=FALSE, fig.align='center', fig.cap="Graphs for CLABSI example data"}
knitr::include_graphics("step3_distributions_zoomed.png")
```
*1. The shape of the distribution: symmetrical/skewed, uniform/peaked/multimodal, whether changes in binwidth show patterning, etc.*
Both histograms seem slightly skewed to the left. This makes sense because we would expect most CLABSI counts to be low with a few higher counts creating a tail, and we cannot have a negative count. The distribution does not appear to be multimodal or have any patterning.
*2. Whether you see any trending, cycles, or suggestions of autocorrelation (we will discuss this more in the next step).*
Both line graphs appear to be trending downward, with Critical Care being more linear than Acute Care.
*3. Whether there are any obvious outliers or inliers---basically, any points deviating from the expected pattern.*
There are no outliers in Acute Care. The two points greater than 15 in Critical Care could be outliers, but they do not appear to be extreme. Note that even if we suspect that point to be an outlier, it is still part of our data. We can look for an explanation for it, but we cannot remove it. We acknowledge its existence now, and remember it if it comes up during later analysis.
Now we will move onto the next step, checking your assumptions.
<br>
## Checking Assumptions
There are three main assumptions that must be met for a SPC chart to be meaningful.
1. We assume that the data does not contain a trend.
2. We assume that the data is independent.
3. We assume that the data is not autocorrelated.
To determine if the first assumption is met, we should look to the areas highlighted in green.
```{r echo=FALSE, fig.align='center', fig.cap="Determining if your data is trending"}
knitr::include_graphics("step3_distributions.png")
```
In the previous step, you already completed a trend test: you looked at the line chart on the right-side panel and decided if it was trending or not. You can tell by eye: does it look like it's trending over a large span of the time series? If so, then it probably is trending.
The Mann-Kendall trend test is often used as well. It is a non-parametric test that can determine whether the series contains a monotonic trend, linear or not. The null hypothesis being tested is that the data does not contain a trend. A caveat is that when sample size is low (n < 20) this test is not useful/accurate.
The Mann-Kendall trend test has been run for you and the results are shown on the left-side panel. For our example CLABSI data was can see the following:
```{r echo=FALSE, fig.align='center', fig.cap="Mann-Kendall test for each department"}
knitr::include_graphics("step3_mann_kendall.png")
```
The Acute Care department passes the trend test at 5%. This means that its p-value (0.006) is less than 0.05. The Critical Care department fails the trend test at 5% because its p-value is 0.08. This is where some flexibility can come into play. This p-value is not that far away from 5%. In fact, another commonly used level for evaluating p-values is the 10% threshold, in which case both would have passed the trend test. Because trends can be an indication of special cause variation in a stable process, standard control limits don't make sense around long-trending data, and calculation of center lines and control limits will be incorrect. **Thus, any SPC tests for special causes other than trending will *also* be invalid over long-trending data.** For the purposes of this example, we will proceed with the analysis.
If the data does have a trend, then a an alternative is to use a run chart with a median slope instead, e.g., via quantile regression. You can generally wait until the process has settled to a new, stable mean and reset the central line accordingly. For a sustained or continuous trend, you can difference the data (create a new dataset by subtracting the value at time *t* from the value at time *t+1*) to remove the trend or use regression residuals to show deviations from the trend.
However, either approach can make the run chart harder to interpret. Perhaps a better idea is use quantile regression to obtain the median line, which allows you to keep the data on the original scale.
The second and third assumptions pertain to independence and autocorrelation. Information about these can be found in the orange shaded regions on the application.
```{r echo=FALSE, fig.align='center', fig.cap="Determining if your data is independent or autocorrelated"}
knitr::include_graphics("step3_autocorrelation.png")
```
Independence and autocorrelation are two important, related terms.
Independence generally means that the value of the data will not change due to other variables or previous data points, ex. rolling a fair die and flipping a coin. The value that the die lands on should not be affected by the coin flip nor the previous value of the die.
Correlation is the tendency for one variable to increase or decrease as a different variable increases. Autocorrelation is a variable that correlates with itself lagged or leading in time, ex. if it rained yesterday, it will be more likely to rain today. If variables are independent, then they do not have any correlation.
For either run charts or control charts, the data points must be independent for the guidelines to be effective. The first test of that is conceptual---do you expect that one value in this series will influence a subsequent value? For example, the incidence of some hospital-acquired infections can be the result of previous infections. Suppose one happens at the end of March and another happens at the start of April in the same unit, caused by the same organism---you might suspect that the monthly values would not be independent.
After considering the context, a second way to assess independence is by calculating the autocorrelation function (acf) for the time series. The ACF for the example CLABSI data can be seen below.
```{r echo=FALSE, fig.align='center', fig.cap="ACF plot for Acute Care unit"}
knitr::include_graphics("step3_autocorrelation_zoomed_AC.png")
```
Note that this plot is for just the Acute Care department. There is a drop-down box that contains the names of the other categories in your column you are comparing across. In our example, we can view the ACF plots for both the Acute Care and Critical Care departments.