Skip to contents

autospc() creates a statistical process control chart from a data frame. Control limits are re-established according to specified rules, by default the Stable Shift Algorithm.

Usage

autospc(
  data,
  x,
  y,
  n,
  s,
  aggregation_na_rm = FALSE,
  chart_type = NULL,
  period_min = 21L,
  baseline_length = NULL,
  shift_rule_threshold = 8L,
  baseline_only = FALSE,
  establish_every_shift = FALSE,
  no_regrets = TRUE,
  overhanging_reversions = TRUE,
  force_restart_at = NULL,
  prevent_establishment_in = NULL,
  restart_after_gap = NULL,
  dispersion_chart_establishment = c("independent", "forced", "shared"),
  na_ends_run = TRUE,
  max_exclusions = 0L,
  highlight_exclusions = TRUE,
  mr_screen_max_loops = 1L,
  centre_line_tolerance = 0,
  floating_median = c("no", "yes", "auto"),
  floating_median_n = 12L,
  plot_chart = TRUE,
  show_limits = TRUE,
  verbosity = 0L,
  log_file_path = NULL,
  keep_candidate_tables = FALSE,
  title = NULL,
  subtitle = NULL,
  use_caption = TRUE,
  override_x_title = NULL,
  override_y_title = NULL,
  override_y_lim = NULL,
  x_break = NULL,
  x_date_format = "%Y-%m-%d",
  x_pad_end = NULL,
  extend_limits_to = NULL,
  display_window = NULL,
  r1_col = "orange",
  r2_col = "steelblue3",
  floating_median_style = list(colour = "firebrick3", linetype = "longdash", linewidth =
    0.75),
  floating_median_labels = c("last", "all", "gaps", "none"),
  point_size = 2,
  line_width_sf = 1,
  include_annotations = TRUE,
  basic_annotations = getRversion() < "4.3.0",
  annotation_size = 3,
  align_labels = FALSE,
  flip_labels = FALSE,
  upper_annotation_sf = NULL,
  lower_annotation_sf = NULL,
  annotation_arrows = FALSE,
  annotation_arrow_curve = 0.3
)

Arguments

data

A data frame. For column requirements by chart type, see vignette("data-requirements", package = "autospc").

x

Name of column (passed using tidyselect semantics) to use as subgroups on the horizontal axis of the chart. Rows with NA in this column are excluded, with a warning; see the Options section of autospc-package to turn the warning off.

y

Name of column (passed using tidyselect semantics) to use as:

  • the variable to be plotted for XMR charts,

  • the measurement for XbarS charts or, where n and s are given, the mean of the measurements each row summarises,

  • count (plotted on the vertical axis) for C and C' charts,

  • numerator of the proportion (plotted on the vertical axis) for P and P' charts,

  • count of events for U and U' charts, which plot the rate y / n.

See vignette("data-requirements", package = "autospc") for more details.

n

Name of column (passed using tidyselect semantics) to use as denominator for P and P' charts, as the area of opportunity each count was made over for U and U' charts, and for XbarS charts as the number of measurements each row summarises. For U and U' charts n need not be a whole number, and its unit sets the unit of the rate: for infections per 1,000 central line days, n is the number of central line days divided by 1,000.
See vignette("data-requirements", package = "autospc") for more details.

s

Name of column (passed using tidyselect semantics) holding the sample standard deviation of the measurements each row summarises, for XbarS charts. Rows that share an x are combined into one subgroup.
See vignette("data-requirements", package = "autospc") for more details.

aggregation_na_rm

Boolean controlling what happens to an observation with no value when aggregating into subgroups. FALSE, the default, makes the whole subgroup missing. TRUE discards the observation and forms the subgroup from the rest. A row is discarded when either its y or its n (for chart types that require it) has no value, so that a subgroup's numerator and denominator always count the same observations. Where every observation in a subgroup is discarded the subgroup itself is missing. Has no effect on data that is already one row per subgroup, or on X and MR charts.

chart_type

The type of chart you wish to plot. Must must have length one. Available options are: "XMR", "X", "MR", "XbarS", "Xbar", "S", "C", "C'", "P", "P'", "U", "U'".

Algorithm Parameters

Parameters that control behaviour of the algorithm used to re-establish control limits.

period_min

The minimum number of points (subgroups) per period, i.e. the minimum number of points required to form control limits.

baseline_length

Integer, the number of points used to form the first calculation period. Defaults to period_min. Where the series has fewer points than this, all of them are used. period_min remains the minimum number of points needed to form limits. A value given as a decimal is truncated to a whole number.

shift_rule_threshold

The minimum number of consecutive points above or below the centre line constituting a shift (or "rule 2") break.

baseline_only

Boolean - if TRUE, do not re-establish control limits, instead extend the limits calculated from the first calculation period.

establish_every_shift

Boolean - whether to bypass the Stable Shift Algorithm and simply re-establish limits at every shift rule break (respecting period_min)

no_regrets

Boolean signifying which version of the algorithm should be used. Defines whether limits can change as more data is added or not.

overhanging_reversions

Boolean determining whether rule breaks in the opposite direction to a rule break triggering a candidate re-establishment prevent limits being re-established, even where they overhang the end of the candidate calculation period. FALSE requires no_regrets = FALSE; with no_regrets = TRUE it is an error.

force_restart_at

Optional, one or more values on the horizontal axis at which the algorithm restarts. The series is analysed in segments, each starting at the first point at or after one of these values, and each segment is analysed as if it were a series of its own: its first calculation period is baseline_length points, and a segment with fewer than period_min points is given no limits. Values outside the data are ignored.

prevent_establishment_in

Optional, a range of the horizontal axis in which the algorithm may not establish new limits, given as two values with NA for an open end, or a list of such ranges. A range includes both its end points. A shift that starts inside a range and continues at least shift_rule_threshold points past the end of that range can still re-establish limits after the end of the range. The first calculation period of the series, and the first after each restart, are not affected. Ranges outside the data are ignored.

restart_after_gap

The number of consecutive points (subgroups) with missing value at or above which the algorithm restarts. Defaults to period_min; Inf turns this feature off. The algorithm restarts at the first point with a value after such a gap, as it does at a value of force_restart_at, and the gap is left without limits. An x value with no row in the data is not part of a gap. For a location-dispersion pair of charts, gaps are counted on the location chart, and both charts restart at the same point. Where a gap ends inside a range given by prevent_establishment_in, the algorithm restarts at the first point with a value after that range instead, and the points between have no limits. Gaps at the start or end of the series are ignored.

dispersion_chart_establishment

How the dispersion chart of a pair (the MR chart of "XMR", the S chart of "XbarS") establishes its limits: "independent" - the algorithm runs on the dispersion chart separately from the location chart, so the two charts' limits can change at different points; "forced" - the dispersion chart uses the location chart's calculation periods, so its limits change where the location chart's do, and in a period where it has fewer points with a value than the location chart, its limits are calculated from fewer than period_min points; "shared" - each calculation period is extended until both charts have at least period_min points with a value in it, and both charts use these periods, so the location chart's limits can differ from those it has with "independent" or "forced". Ignored, with a warning, for a chart type that is not a pair.

SPC Parameters

Parameters that control how centre line and control limits are established for each period, and details of how SPC rules are applied

na_ends_run

Boolean determining whether a missing point starts a new run, for the purpose of the shift rule. TRUE minimises the risk of a false positive shift rule break arising from missing data; FALSE minimises the risk of a false negative.

max_exclusions

The maximum number of extreme points to exclude from limit calculations. The default, 0, excludes none.

highlight_exclusions

Boolean signifying whether excluded points are greyed out.

mr_screen_max_loops

Integer or Inf specifying maximum number of times to recursively ignore moving ranges above the upper range limit when estimating a standard deviation from them: the moving ranges of the data for X charts, and of the points' z-scores for C', P' and U' charts. 0 turns the screening off, as Laney (2002) describes the P' and U' charts. Note this does not affect the calculation of the upper range limit on the mr chart.

centre_line_tolerance

Minimum difference between a point's vertical position and the centre line to count as "on the centre line" for the purposes of shift rule breaks

floating_median

Whether to add a floating median line to the chart, calculated based on the final floating_median_n data points on the chart: "no" - do not display a floating median, "yes" - display a floating median, "auto" - display a floating median if and only if there are sufficient data to form a median, and at least one point that is part of a shift rule break in the final floating_median_n data points on the chart.

floating_median_n

The number of points to use for calculation of the floating median, if present. Where the series holds fewer non-missing points than this, there are none to take a median over, so none is drawn: "yes" warns, and "auto" is silent.

Output Type

Arguments that control how the result is outputted

plot_chart

Boolean specifying whether to plot the chart. If not, the subgroup-aggregated data is returned with centre line, control limits and other analytic output appended as columns.

show_limits

Boolean controlling whether or not to display centre line and control limits

verbosity

Integer 0-2 specifying how talkative the algorithm is in the standard output log; the higher the number the more information is provided, none if 0. A value outside the range is taken as the nearest end of it, and a value between two whole numbers as the next one up.

log_file_path

if not NULL (the default), path to save log file to. The file extension provided (.rds or .csv) determines the type of file the log data is saved to. Full log data is saved, regardless of verbosity.

keep_candidate_tables

Boolean specifying whether to retain the table of limits for each candidate calculation period the algorithm considers. The candidates themselves are recorded either way, with the reasons they were accepted or rejected; this is the full table of limits for each, and therefore makes an analysed chart several times larger.

Chart Appearance

Arguments that control aspects of chart visualisation

title

Optional string specifying chart title. Overrides data$title.

subtitle

Optional string specifying subtitle. Overrides data$subtitle.

use_caption

Boolean controlling whether the caption is displayed.

override_x_title

String specifying horizontal axis label.

override_y_title

String specifying vertical axis label.

override_y_lim

Optional numeric specifying the ends of the vertical axis. A single number specifies the upper end. A vector of two numbers specifies the lower and upper ends, and NA in either position leaves that end as the chart would have set it. A range that would leave a data point outside the axis is an error; however, control limits and annotations may fall outside the range.

x_break

Optional numeric specifying spacing of horizontal axis breaks.

x_date_format

Optional string format for date labels on horizontal axis. Passed to scales::date_format.

x_pad_end

Optional, specifies a minimum end point for the horizontal axis.

extend_limits_to

Optional, specifies a point on the horizontal axis to extend the final limits out to

display_window

Optional, two values on the horizontal axis giving the start and end of the range to show, with NA for an end to leave where the chart would put it. The analysis uses the whole series; the plot is zoomed to this range, and the centre line labels are placed for it. The vertical axis is still set from the whole series, and override_y_lim is checked against the points in the range. The floating median is drawn only when the range reaches the end of the data.

r1_col

Highlight colour for breaks of rule 1 (points outside the control limits)

r2_col

Highlight colour for breaks of rule 2 (shifts)

floating_median_style

A list setting how the floating median is drawn, with any of the elements colour, linetype and linewidth. Elements not given take their defaults: "firebrick3", "longdash" and 0.75. The width is multiplied by line_width_sf, as the other lines are. The median's label is drawn in colour.

floating_median_labels

Which floating medians to label, where a series restarts and so has more than one: "last" - the median of the last segment of the series only; "all" - every median; "gaps" - the median of the last segment, and every median whose last point is followed by a gap of at least restart_after_gap points with no value; "none" - no median. In facet_stages(), this applies within each facet.

point_size

Size of plot points, defaults to 2. See aes_linetype_size_shape for more details.

line_width_sf

Numeric scale factor for plot line widths.

include_annotations

Boolean specifying whether to show centre line labels

basic_annotations

Boolean specifying whether to force use of basic annotation positioning. When TRUE, suggested packages ggrepel and ggpp are not required, but annotation arrows are not supported. Defaults to TRUE for R versions prior to 4.3, FALSE otherwise.

annotation_size

Text size for centre line labels

align_labels

Boolean specifying whether or not to align centre line labels at a fixed vertical position

flip_labels

Boolean specifying whether or not to place centre line labels on different sides of the centre line depending on the direction of change from the previous period

upper_annotation_sf

Numeric scale factor specifying upper vertical position of centre line labels as a multiple of the upper control limit. A negative limit is multiplied by 2 - upper_annotation_sf.

lower_annotation_sf

Numeric scale factor specifying lower vertical position of centre line labels as a multiple of the lower control limit. A negative limit is multiplied by 2 - lower_annotation_sf.

annotation_arrows

Boolean specifying whether or not to display arrows connecting centre line labels to the centre line they refer to

annotation_arrow_curve

Numeric curvature of the annotation arrows

Value

With plot_chart = TRUE (the default), an autospc_plot: a ggplot of the chart, or of the pair for chart_type = "XMR" or "XbarS", which also carries the analysed chart objects it was drawn from and the parameters it was drawn with. Anything that works on a ggplot works on it, including +, print() and ggplot2::ggsave(), and as.data.frame() gives the analysis behind it.

With plot_chart = FALSE, a data frame: the subgroup-aggregated data with the centre line, the control limits and the rest of the analytic output appended as columns. series holds the values analysed and plotted, which are the moving ranges on an MR chart, the subgroup standard deviations on an S chart, percentages on a P or P' chart and rates on a U or U' chart; y holds the values as supplied and aggregated.

Examples

# Using a C' chart to track changes in the count of monthly attendance
autospc(
  ed_attendances_monthly,
  chart_type = "C'",
  x = month_start,
  y = att_all,
  max_exclusions = 3L
)
#> Registered S3 methods overwritten by 'ggpp':
#>   method                  from   
#>   heightDetails.titleGrob ggplot2
#>   widthDetails.titleGrob  ggplot2


# Using a P' chart to track changes in the percentage admitted within 4 hours
autospc(
  ed_attendances_monthly,
  chart_type = "P'",
  x = month_start,
  y = within_4h,
  n = att_all,
  max_exclusions = 3L
)


# using a shift_rule_threshold of 7 when tracking monthly attendance
autospc(
  ed_attendances_monthly,
  chart_type = "C'",
  x = month_start,
  y = att_all,
  max_exclusions = 3L,
  shift_rule_threshold = 7
)