--- title: "Disparities, benchmarks and checks of a reported number" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Disparities, benchmarks and checks of a reported number} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} # the vignette runs in full in GitHub CI and for the package tarball (NOT_CRAN), # on r-universe (MY_UNIVERSE), on the package website (IN_PKGDOWN) and in an # interactive session; when CRAN re-builds it in its check, none of these is set # and only this chunk runs if (!interactive() && !any(nzchar(Sys.getenv(c("NOT_CRAN", "MY_UNIVERSE", "IN_PKGDOWN"))))) { knitr::knit_exit() } knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 6.5, fig.height = 4, fig.align = "center", dpi = 72) options(width = 88) set.seed(1) library(crimlab) ``` Tests of disparity in stops and outcomes, and checks that a published ratio or table says what it is taken to say. Each section is one help page: what the function is for, the example of its help page as it runs, and the plot of its result where the package draws one. `?name` gives the arguments and the value in full. # Disparities ## Veil-of-darkness test `vodtst()`: Compares each group's share of stops made in daylight, when a driver's race can be seen, with its share in darkness, when it cannot. The ratio of the two odds against a reference group is the factor by which visibility changes that group's chance of being stopped; 1 means no change. ```{r vodtst} vodtst(day = c(white = 600, black = 400), night = c(white = 700, black = 300)) # one table of groups by day and night stops <- data.frame(day = c(600, 400), night = c(700, 300), row.names = c("white", "black")) vodtst(stops) ``` ## Risks behind an odds ratio `orrisk()`: An odds ratio is not a relative risk: it lies further from 1, and by more the more common the outcome. Given the odds ratio, the overall rate of the outcome and the share exposed, this returns the two risks and the relative risk they imply. See `proof("orrisk")`. ```{r orrisk} orrisk(or = 3, rate = 0.4, share = 0.5) ``` ## Outcome test `outtst()`: The stop rate and the hit rate of a group searched whenever the chance of guilt exceeds a threshold. Hit rates compare averages, not thresholds: two groups held to the same threshold can show different hit rates, and a group held to a lower threshold can show the higher one (infra-marginality). See `proof("outtst")`. ```{r outtst} outtst(q = c(0.1, 0.5, 0.9), t = 0.3) ``` ## Tests of discrimination in searches: hit rates, thresholds, rank order `thrtst()`: Asks whether the police search people of one group on less evidence than people of another. Three tests read the same counts of stops, searches and successful searches ("hits", contraband found): ```{r thrtst} # stops, searches and hits of two groups in four areas d <- data.frame( grp = rep(c("a", "b"), 4), area = rep(1:4, each = 2), stops = c(1200, 800, 900, 1100, 1500, 700, 1000, 1000), srch = c(60, 70, 50, 95, 80, 66, 52, 90), hits = c(24, 18, 19, 25, 30, 17, 21, 24) ) thrtst(d$stops, d$srch, d$hits, d$grp, area = d$area) # the rank-order test needs the officers' groups thrtst(c(100, 100, 100, 100), c(10, 20, 30, 10), c(5, 5, 5, 5), grp = c(1, 1, 2, 2), off = c("x", "y", "x", "y"))$rank # the joint test of three officer groups thrtst(rep(600, 9), c(72, 48, 60, 60, 72, 48, 48, 60, 72), rep(c(36, 24, 30), 3), grp = rep(1:3, each = 3), off = rep(c("a", "b", "c"), 3), rank = "joint")$rank ``` ```{r thrtst-plot} res <- thrtst(d$stops, d$srch, d$hits, d$grp, area = d$area) plot(res) ``` ## Internal benchmarking of officers `ibench()`: Asks whether an officer stops more people of a group (or searches, arrests, uses force more often) than other officers do in the same circumstances. Officers work different places and hours, so each officer's stops are compared not with all other stops but with the other officers' stops weighted to look like this officer's: the propensity `e(x)` that a stop with circumstances `x` (place, hour, day, reason) is this officer's comes from a logistic regression on `x` (over all stops), and each other officer's stop gets the weight `e / (1 - e)`, the weights of the effect on the treated (Ridgeway and MacDonald 2009). The benchmark is the weighted share of the outcome among those stops, and the z statistic compares the officer's share with it, with the variance of a proportion for the officer and, for the benchmark, that of a proportion over its effective number of stops, (sum w)^2 / sum w^2. With many officers some will stand out by chance: `q` is the false discovery rate of Benjamini and Hochberg (1995) over the officers tested, and `flag` marks those with `q` below `fdr`. ```{r ibench} set.seed(2) n <- 3000 off <- sample(sprintf("o%02d", 1:12), n, TRUE) night <- rbinom(n, 1, ifelse(off %in% c("o01", "o02"), 0.7, 0.3)) y <- rbinom(n, 1, plogis(-1 + night + 0.8 * (off == "o03"))) ibench(y, off, data.frame(night), minn = 50) ibench(y, off, data.frame(night), minn = 50, dr = TRUE)$tab ``` ```{r ibench-plot} res <- ibench(y, off, data.frame(night), minn = 50) plot(res) ``` ## Benchmark decomposition of a disparity `dspbm()`: Splits each group's disparity in force per resident, against a reference group, into a disparity in contact per resident times a disparity in force per contact. The split is a product, never a sum. See `proof("dspbm")`. ```{r dspbm} dspbm(pop = c(a = 9000, b = 1000), contact = c(a = 900, b = 300), force = c(a = 9, b = 6)) ``` ## Dyadic offending rates `dyadrt()`: Offences by one group against another, as a rate per member of the offending group and as a rate per offender-victim pair exposed. The rate per offender rises with the size of the victim group even when offenders choose victims at random; the rate per pair does not. See `proof("dyadrt")`. ```{r dyadrt} pop <- c(a = 800, b = 200) dyadrt(count = outer(pop, pop) / 1000, pop = pop) ``` # Checks ## Which labelling reproduces a reported contrast? `relchk()`: A reported odds ratio, risk ratio or risk difference depends on which group is the reference, which outcome is the event and which margin of the table holds the groups. `relchk()` recomputes the contrast from the table under every such reading and says which ones reproduce the reported value: the labelling the report states, another one, or none. ```{r relchk} tab <- matrix(c(20, 10, 80, 90), 2, dimnames = list(c("A", "B"), c("yes", "no"))) # 2.25 is the odds ratio of A against B for "yes" relchk(tab, 2.25, ref = "B", event = "yes") # 0.44 is the same contrast read with the reference group swapped relchk(tab, 0.44, ref = "B", event = "yes") # a risk ratio reported as an odds ratio relchk(tab, 2.0, type = "or", digits = 1) ``` ```{r relchk-plot} res <- relchk(tab, 2.0, type = "or", digits = 1) plot(res) ``` ## Audit categorical inputs before an analysis `catchk()`: Reports, for each variable, what the functions of this package would make of it: its storage type, its levels and their counts, missing values, unused levels, levels counted fewer than `nmin` times, labels that differ only by case or white space, a 0/1 or logical coding, integer codes that look like categories, value labels (as haven makes) that do not match the values, and which level a default would take as the reference, and why. Nothing is changed. ```{r catchk} d <- data.frame(sex = c("Male", "male", "Female", "Female", NA), custody = c(TRUE, FALSE, TRUE, TRUE, FALSE), court = c(1L, 2L, 2L, 3L, 1L)) catchk(d, nmin = 2) catchk(factor(c("b", "a", "b"), levels = c("a", "b", "c")), ref = "b") ``` ## Declare rules a table must satisfy, and check them `rul()`, `valrules()`: `rul()` declares one rule: a name, a function that says whether the data pass, the column it reads (or the whole table), how serious a failure is and the message to give. `valrules()` runs a list of rules on a data frame and returns the ones that failed, with the rows that broke them. The ready-made rules (`ruleinset()` and the others) cover the usual checks, so that they are written once and not by hand. ```{r rul} d <- data.frame(id = c(1, 2, 2, 4), age = c(34, -1, 51, NA), charge = c("assault", "theft", "theft", "arson")) r <- list( rul("age_not_negative", function(v) is.na(v) | v >= 0, col = "age", msg = "an age is negative"), ruleuniq("id", sev = "fatal"), rulenull("age"), ruleinset("charge", c("assault", "theft", "drugs")) ) v <- valrules(d, r) v v[["id_unique"]][["rows"]] # a table that passes length(valrules(d[1, ], r)) # a rule written as data valrules(d, list(rule = "btw", col = "age", lo = 0, hi = 120)) try(rul("", function(v) TRUE)) ``` ## Ready-made rules `ruleinset()`, `rulebtw()`, `rulenull()`, `ruleuniq()` and others: The checks that account for most of what a table is asked: a value in a set, a number in a range, no missing value, no repeated identifier, a pattern, an order, an outlier, complete rows, distinct rows, a number of columns. Each returns a rule for `valrules()`, as `rul()` does. ```{r ruleinset} d <- data.frame(year = c(2019, 2020, 2021, 2021), n = c(410, 395, 9000, 402), div = c("11", "14", "14", "5X")) valrules(d, list( rulebtw("year", 2000, 2026), ruleincr("year", strict = TRUE), rulemad("n", 5), rulerx("div", "^[0-9]{2}$"), ruledstn(c("year", "div")), rulecolcnt(3), rulecmpl() )) try(rulebtw("year", 2026, 2000)) ``` # Shares ## Share of a total, in percent `shrs()`: Expresses each count as a percentage of a total (for example each division's share of all stops, or each offence's share of all admissions), with a Wilson confidence interval. A share's denominator is the total of the same events, so shares over a complete grouping sum to 100. Use a rate (such as `grprr()`) instead when the denominator is a population; "40% of stops" and "40 stops per 1,000 residents" are different claims. ```{r shrs} # simulated stops by division stops <- data.frame(division = c("North", "South", "East"), stops = c(412, 77, 3)) shrs(stops, stops, by = "division") shrs(stops, "stops", by = "division", total = 10000) shrs(c(murder = 3, robbery = 7)) try(shrs(c(5, 2), total = 4)) ```