--- title: "Environmental exposure and crime" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Environmental exposure and crime} %\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) ``` Designs that estimate the effect of an environmental exposure on crime: fixed effects, instruments and their diagnostics. 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. ## Poisson pseudo-maximum likelihood with absorbed fixed effects `ppmlfe()`: Fits a count model with one or two sets of fixed effects, such as place and day, absorbed rather than estimated as columns, an optional exposure (offset) and robust standard errors of several kinds. This is the estimator of Bondy, Roth and Sager (2020): daily counts of offences by ward, ward fixed effects and time effects, and ward population as the offset. It serves any count by place and period against any exposure. ```{r ppmlfe} # simulated counts in 12 areas over 40 days set.seed(1) d <- expand.grid(day = 1:40, area = 1:12) d$pop <- rep(round(runif(12, 1000, 5000)), each = 40) d$pm <- rnorm(nrow(d), 20, 5) d$temp <- rnorm(nrow(d), 15, 4) d$crimes <- rpois(nrow(d), d$pop / 1000 * exp(0.02 * d$pm + 0.01 * d$temp + rnorm(12, 0, 0.3)[d$area])) f <- ppmlfe(d, "crimes", c("pm", "temp"), fe = c("area", "day"), expo = "pop") f plot(f) # two-way clustering by area and day; Newey-West within areas summary(ppmlfe(d, "crimes", c("pm", "temp"), fe = c("area", "day"), expo = "pop", se = "twoway")) summary(ppmlfe(d, "crimes", c("pm", "temp"), fe = c("area", "day"), expo = "pop", se = "nw", time = "day", lag = 3)) ``` ```{r ppmlfe-plot} plot(f) ``` ## Two-stage least squares with absorbed fixed effects `ivfe()`: Estimates the effect of an exposure that is measured with error or shares unmeasured causes with the outcome, by instrumental variables: each endogenous column is first regressed on the excluded instruments and the controls (the first stage), and the outcome on the fitted values and the controls (the second stage), with one or two sets of fixed effects absorbed throughout. This is the linear estimator of Herrnstadt, Heyes, Muehlegger and Saberian (2019): the log of daily assaults near each monitor on ozone, instrumented by a westerly wind, with monitor and time fixed effects and errors clustered by monitor and by date. Without `endo` and `inst` it is least squares with the fixed effects. ```{r ivfe} # simulated: an unmeasured daily shock u raises both the exposure and # the outcome; the wind moves the exposure only set.seed(2) d <- expand.grid(day = 1:60, area = 1:12) d$wind <- runif(nrow(d), 0, 360) w <- windiv(d$wind, width = 90) d <- cbind(d, w) u <- rnorm(nrow(d)) d$oz <- 3 * w[, 1] - 2 * w[, 2] + u + rnorm(nrow(d)) d$out <- 0.5 * d$oz + u + rnorm(nrow(d)) f <- ivfe(d, "out", endo = "oz", inst = colnames(w), fe = c("area", "day"), se = "twoway") f f$first f$fstab plot(f) # shaped as Chen and Li (2020, equations 4-5, p. 4): county-season-year # cells, the triple difference (treated state x summer x after) as the # instrument of the AQI, county-by-year and state-by-season effects # absorbed, the county-by-season effects as indicator columns, errors # clustered by state (simulated) set.seed(14) g <- expand.grid(county = 1:30, season = c("s", "w"), year = 2000:2007) g$state <- (g$county - 1) %/% 3 + 1 g$ddd <- as.numeric(g$state <= 5 & g$season == "s" & g$year >= 2003) g$aqi <- 50 - 6 * g$ddd + rnorm(nrow(g), 0, 3) g$lcrime <- 2 + 0.01 * g$aqi + rnorm(nrow(g), 0, 0.1) g$cy <- paste(g$county, g$year) g$ss <- paste(g$state, g$season) # county x summer, less the first county of each state (the rest is # absorbed by the two sets of effects) for (k in unique(g$county[g$county %% 3 != 1])) { g[[paste0("cs", k)]] <- as.numeric(g$county == k & g$season == "s") } ivfe(g, "lcrime", endo = "aqi", inst = "ddd", x = grep("^cs", names(g), value = TRUE), fe = c("cy", "ss"), clus = "state")$coef[1, ] # shaped as Carrillo, Lopez-Luzuriaga and Malik (2018): the difference # in differences of equation (4), p. 7 (city-day-hour counts, the # treated city after the start, year-month and hour-by-weekday # effects, errors clustered by week) and the spatial regression # discontinuity of equation (6), p. 8 (counts by distance bin, the # inside indicator, a line on each side, within a window) set.seed(15) h <- expand.grid(city = c("quito", "other"), day = 1:120, hour = 0:23) h$after <- as.numeric(h$day > 60) h$treat <- h$after * (h$city == "quito") h$ym <- (h$day - 1) %/% 30 h$hd <- paste(h$hour, h$day %% 7) h$week <- (h$day - 1) %/% 7 h$crimes <- rpois(nrow(h), 2 + 0.3 * h$treat) h$q <- as.numeric(h$city == "quito") ivfe(h, "crimes", x = c("treat", "q"), fe = c("ym", "hd"), clus = "week")$coef[1, ] b <- data.frame(dist = seq(-975, 975, by = 50)) b$inside <- as.numeric(b$dist > 0) b$dside <- b$dist * b$inside b$n <- rpois(nrow(b), 20 + 5 * b$inside) b$one <- 1 ivfe(b[abs(b$dist) <= 800, ], "n", x = c("inside", "dist", "dside"), fe = "one", se = "hc1")$coef[1, ] ``` ```{r ivfe-plot} plot(f) ``` ## Instrumental variables for a count outcome with fixed effects `ppmlcf()`: Instruments an exposure in the count model of `ppmlfe()`, in one of two ways (`how`). The first stages regress each endogenous column on the excluded instruments and the controls with the fixed effects (as in `ivfe()`). Then: ```{r ppmlcf} # simulated counts; the shock u raises pollution and crime together set.seed(3) d <- expand.grid(day = 1:50, area = 1:15) d$wind <- runif(nrow(d), 0, 360) w <- windiv(d$wind, width = 90) d <- cbind(d, w) u <- rnorm(nrow(d), 0, 0.5) d$pm <- 2 * w[, 1] - w[, 3] + u + rnorm(nrow(d)) d$crimes <- rpois(nrow(d), exp(1 + 0.1 * d$pm + 0.5 * u)) f <- ppmlcf(d, "crimes", endo = "pm", inst = colnames(w), fe = c("area", "day"), nboot = 49, seed = 1) f plot(f) # the paper's plug-in, with its naive errors summary(ppmlcf(d, "crimes", endo = "pm", inst = colnames(w), fe = c("area", "day"), how = "plug", se = "naive")) ``` ```{r ppmlcf-plot} plot(f) ``` ## Exponential-mean GMM for a count with an endogenous exposure `expgmm()`: Estimates E(y | x) = exp(x'b + log(expo)) with some regressors endogenous, by the generalised method of moments on the first-order moment conditions alone, as Mullahy (1997) and Windmeijer and Santos Silva (1997) set it out: sum_i z_i u_i(b) = 0 with `z` the excluded instruments and the exogenous regressors. The residual (`err`): ```{r expgmm} # simulated: an unmeasured shock v multiplies the mean and moves the # exposure; two instruments, day effects, errors clustered by area set.seed(4) d <- expand.grid(day = 1:10, area = 1:40) d$z1 <- rnorm(nrow(d)) d$z2 <- rnorm(nrow(d)) v <- rnorm(nrow(d), 0, 0.5) d$pm <- 0.6 * d$z1 - 0.4 * d$z2 + v + rnorm(nrow(d), 0, 0.5) d$crimes <- rpois(nrow(d), exp(0.5 + 0.2 * d$pm + v)) f <- expgmm(d, "crimes", endo = "pm", inst = c("z1", "z2"), fe = "day", clus = "area") f f$j plot(f) # the additive residual, one step summary(expgmm(d, "crimes", endo = "pm", inst = c("z1", "z2"), fe = "day", clus = "area", err = "add", step = "one")) ``` ```{r expgmm-plot} plot(f) ``` ## The parts of a fitted regression `racc()`: The fits of `ppmlfe()`, `ivfe()`, `ppmlcf()`, `expgmm()`, `fepnl()`, `gmmpnl()`, `didfe()`, `rdloc()` and `sarml()` are lists, and the usual accessors read them: `coef()` gives the estimates by term, `confint()` their intervals, `vcov()` the covariance matrix of the estimates and `nobs()` the rows the fit used. ```{r racc} set.seed(1) d <- data.frame(u = rep(1:20, each = 6), x = rnorm(120)) d$y <- 1 + 0.5 * d$x + rnorm(120) f <- ivfe(d, "y", x = "x", fe = "u") coef(f) confint(f) vcov(f) nobs(f) ``` ```{r racc-plot} plot(f) ``` ## Wind-direction instruments `windiv()`: Turns wind directions into indicators of the sector the wind blows from, one sector left out, optionally one set per area so that the same wind may act differently in different parts of a city; from hourly directions it first makes one per day. ```{r windiv} windiv(c(10, 100, 200, 300)) # the paper's whole-degree quadrants: 90 is in the first windiv(c(90, 91), edges = "paper") # quadrants by region, as in London windiv(c(10, 100, 200, 300), area = c("east", "east", "west", "west")) # one westerly sector windiv(c(230, 300), sect = c(225, 285)) # hours to days: 350 and 10 degrees average to north windiv(c(350, 10, 100, 120), by = c(1, 1, 2, 2)) windiv(c(350, 10, 100, 120), by = c(1, 1, 2, 2), share = TRUE) ``` ## Temperature inversions `invsn()`: The instrument of Bondy, Roth and Sager (2020, p. 566-567): "the continuous difference between temperatures at the ground level and temperatures at circa 750 m altitude (925 hectopascals (hPa) pressure level)". On most days the air cools with height; in an inversion it is warmer above than at the ground, and pollutants are trapped near the ground. ```{r invsn} invsn(c(10, 5, 2), c(8, 6, 2)) # three-hourly readings, one row per day: inverted when every reading is invsn(c(1, 2, 3, 1, 2, 3), c(4, 5, 6, 4, 1, 6), by = c(1, 1, 1, 2, 2, 2)) invsn(c(10, 5, 2), c(8, 6, 2), sign = "ground", brk = c(-Inf, -1, 0, Inf)) # the share of days without an inversion and the support (check 3) attr(invsn(c(10, 5, 2), c(8, 6, 2)), "diag") ``` ## Downwind exposure: places downwind of sources of pollution `dwnexp()`: Whether each place lies downwind of sources of pollution in each period, and how far off the wind's line it lies: the instruments of the papers that let the wind carry smoke from fires that move from day to day (Bao and Da 2026) or from a fixed set of sources (Ayesh 2023), for the instrumental-variable estimators `ivfe()`, `ppmlcf()` and `expgmm()`. ```{r dwnexp} # two plumes on day 1, one on day 2; four county points (planar, km) s <- data.frame(x = c(0, 50, 0), y = c(0, 0, 0), day = c(1, 1, 2), from = c(180, 270, 0)) p <- data.frame(x = c(0, 100, 0, -80), y = c(100, 10, -60, 0)) r <- dwnexp(s$x, s$y, s$day, s$from, p$x, p$y) r # the county-month count of downwind days (Bao and Da 2026, eq 1) r$month <- 1 aggregate(any ~ id + month, r, sum) # Ayesh's instrument: the angle off the mean wind of the source # districts, times the mean distance to them dwnexp(c(0, 10), c(0, 0), c(2020, 2020), c(240, 250), c(30, -30, 5), c(20, -20, 0), rule = "angle") # the wedge against a square county sq <- data.frame(id = 1, x = c(-10, 10, 10, -10), y = c(40, 40, 60, 60)) dwnexp(0, 0, NULL, 180, sq$x, sq$y, sq$id, rule = "wedge", rad = 100) ``` ## The tailwind component of the wind along a flight course `tailwd()`: The part of the wind that blows along a course, positive for a tailwind, from which Hener (2022) builds the instrument of the landing direction at Frankfurt Airport: aircraft land westbound (course 250 degrees) unless the tailwind on that course exceeds 2.6 m/s, so the days of the eastbound approach, and which municipalities lie under the noise, follow from the wind. ```{r tailwd} # wind from the east (70 degrees) at 4 m/s is a 4 m/s tailwind westbound tailwd(c(70, 340, 250), c(4, 4, 4)) # hourly readings to the daily maximum, then Hener's instrument for a # municipality under the eastbound approach tw <- tailwd(c(70, 90, 250, 260), c(3, 2, 5, 1), by = c(1, 1, 2, 2)) as.integer(tw$tw > 2.6) ``` ## Irrelevant-day placebo `plcday()`: Refits an estimator with the exposure taken from other days of the same place, leads and lags in one call, and returns one table of coefficients, the same day first. This is the placebo of Bondy, Roth and Sager (2020, table A1 and footnote 27: 7, 31 and 365 days back and forward) and of Herrnstadt, Heyes, Muehlegger and Saberian (2019, table 9: 100 days); shifts = c(-365, -100, -31, -7, 7, 31, 100, 365) runs both. ```{r plcday} # simulated: crime responds to same-day pollution only set.seed(4) d <- expand.grid(day = 1:80, area = 1:12) d$pm <- rnorm(nrow(d), 20, 5) d$crimes <- rpois(nrow(d), exp(0.5 + 0.03 * d$pm)) p <- plcday(d, "pm", "area", "day", shifts = c(-7, 7), y = "crimes", x = "pm", fe = c("area", "day")) p plot(p) ``` ```{r plcday-plot} plot(p) ``` ## The upwind and downwind design around a road or a point source `updwn()`: Compares counts on the downwind side of a pollution source with counts on its upwind side on the same day, the design of Herrnstadt, Heyes, Muehlegger and Saberian (2021) for the interstates of Chicago (first as Herrnstadt and Muehlegger 2015). The upwind side shares the day's weather and everything else about the day near that road, so it is the control for the downwind side; the side fixed effects take out what differs between the two sides on every day. ```{r updwn} # simulated: a road along the x axis, areas on both sides, crime up 10% # on the downwind side set.seed(5) a <- data.frame(area = 1:40, ax = runif(40, 0, 5000), ay = runif(40, -4000, 4000)) d <- merge(a, data.frame(day = 1:120)) d$wind <- runif(120, 0, 360)[d$day] blowsn <- cos((d$wind + 180) * pi / 180) # +1 when the wind blows north dn <- abs(d$ay) < 1600 & ((d$ay > 0 & blowsn > 0.5) | (d$ay < 0 & blowsn < -0.5)) d$crimes <- rpois(nrow(d), 3 * (1 + 0.1 * dn)) road <- data.frame(x0 = 0, y0 = 0, x1 = 5000, y1 = 0) u <- updwn(d, "crimes", "ax", "ay", "day", "wind", road, band = 1600, offs = c(-1600, 0, 1600)) u plot(u) # the Poisson model and two distance rings summary(updwn(d, "crimes", "ax", "ay", "day", "wind", road, band = 1600, norm = "pois", dist = c(0, 500, 1600))) ``` ```{r updwn-plot} plot(u) ``` ## Join an exposure table to counts by place and day `expjn()`: Makes the analysis table of the estimators of this family: the rows of the outcome table (place, day, count, ...) with the exposure of the same place and day joined on. Exposure may come from monitors (assigned to areas beforehand, for example by inverse squared distance from the three nearest, as Bondy, Roth and Sager do) or from crimlab's dispersion functions (`gplume()`, `plmfld()`). ```{r expjn} ex <- data.frame( area = c("a", "a", "b"), day = c(1, 2, 1), pm = c(10, 12, 8) ) oc <- data.frame(area = c("a", "a", "b", "b"), day = c(1, 2, 1, 2), crimes = c(3, 1, 0, 2)) j <- expjn(ex, oc) j j$data ``` ## Smoke instruments from plume data `smkiv()`: Builds the wildfire-smoke instruments of the recent papers from a daily smoke-plume record by place: the presence of a plume; the presence adjusted to the plumes that reached the ground; plume density classes; smoke-attributable fine particles; and counts by month. ```{r smkiv} # simulated plumes and PM2.5 in two places over 120 days set.seed(6) d <- data.frame(place = rep(c("a", "b"), each = 120), day = rep(as.Date("2024-06-01") + 0:119, 2)) d$plume <- rbinom(240, 1, 0.2) d$pm <- rnorm(240, 8, 2) + d$plume * rbinom(240, 1, 0.5) * 15 d$near <- ifelse(d$place == "a", "b", "a") s <- smkiv(d, "plume", "place", "day", pm = "pm", adj = "own") table(raw = d$plume, adjusted = s$smoke) head(smkiv(d, "plume", "place", "day", pm = "pm", adj = "nbr", nbr = "near")) ``` ## Runs of exposed days `exprun()`, `runfx()`: Counts, for each place and day, how many days in a row the place has been exposed (smoke present, pollution above a threshold), and makes the indicators of the first, second, ... day of a run. `runfx()` fits a model with them: the effect by day in the run, as Lee and Lee (2026, equation 3, p. 12) estimate it, Crime = b1 Day1 + b2 Day2 + b3 Day3+ + ..., which shows whether the effect fades as people adapt (it rises on the first and second smoke days and falls from the third in their 21 cities). ```{r exprun} d <- data.frame(area = 1, day = 1:8, smoke = c(0, 1, 1, 1, 1, 0, 1, 0)) cbind(d, exprun(d, "smoke", "area", "day")) # simulated: crime up on the first two smoke days set.seed(7) d <- expand.grid(day = 1:120, area = 1:12) d$smoke <- rbinom(nrow(d), 1, 0.3) r <- exprun(d, "smoke", "area", "day") d$crimes <- rpois(nrow(d), exp(1 + 0.2 * r$run1 + 0.1 * r$run2)) f <- runfx(d, "crimes", "smoke", "area", "day", fe = c("area", "day")) f plot(f) ``` ```{r exprun-plot} plot(f) ``` ## Effects by a moderator, with the joint test of equality `hetfx()`: Estimates the effect of an exposure separately for each level of a moderator (household wealth, income quantile, rural or urban, offence context) and tests whether the effects are equal. ```{r hetfx} # simulated: pollution matters in poor areas only set.seed(8) d <- expand.grid(day = 1:60, area = 1:20) d$poor <- ifelse(d$area <= 10, "poor", "not poor") d$pm <- rnorm(nrow(d), 20, 5) d$crimes <- rpois(nrow(d), exp(0.5 + 0.04 * d$pm * (d$poor == "poor"))) h <- hetfx(d, "pm", "poor", y = "crimes", x = "pm", fe = c("area", "day")) h plot(h) ``` ```{r hetfx-plot} plot(h) ``` ## The time-stratified case-crossover design `ccross()`: Compares each day's count with the counts of the same place on the other days of its stratum, the case-crossover design for counts: a Poisson model with one fixed effect per stratum, which gives the same coefficients as the conditional Poisson model. Ju et al. (2026, equations 1 and 2, p. 7) use the space-time stratum "one region nested in the same weekday of same month from the same year" (`strat = "ymw"`, the default), a control function for wildfire PM2.5 driven by wind speed, the 2-day moving average of exposure (`ma`), and errors clustered by calendar year-month (the default `clus` here). ```{r ccross} set.seed(9) d <- expand.grid(day = as.Date("2023-01-01") + 0:364, area = 1:4) d$pm <- rnorm(nrow(d), 15, 4) d$crimes <- rpois(nrow(d), exp(1 + 0.02 * d$pm)) ccross(d, "crimes", "area", "day", ma = "pm", x = "pm") # shaped as Burkhardt et al. (2019, JEEM, equation 1, p. 5): county-day # counts on PM2.5 and ozone together, county-by-year-by-month-by-weekday # effects, errors clustered by county (simulated) d$o3 <- rnorm(nrow(d), 0.03, 0.01) ccross(d, "crimes", "area", "day", x = c("pm", "o3"), clus = "area") # shaped as Han et al. (2026, Methods p. 2 and table 1): city-day # counts, same-weekday-same-month strata, a holiday indicator, natural # splines of temperature (6 df) and humidity (3 df), NO2 at lag 0, the # percent change per interquartile range (simulated) d$no2 <- rnorm(nrow(d), 30, 10) d$temp <- 15 + 10 * sin(2 * pi * as.numeric(d$day) / 365) + rnorm(nrow(d)) d$rh <- runif(nrow(d), 30, 90) d$hol <- as.numeric(format(d$day, "%m-%d") %in% c("01-01", "10-01")) d$crimes <- rpois(nrow(d), exp(1 + 0.004 * d$no2)) h <- ccross(d, "crimes", "area", "day", x = c("no2", "hol"), ns = c(temp = 6, rh = 3), clus = "area") b <- h$coef[h$coef$term == "no2", ] 100 * (exp(c(b$est, b$lo, b$hi) * IQR(d$no2)) - 1) plot(h, terms = "no2") ``` ```{r ccross-plot} plot(h) ``` ## Two exposures together: their interaction and the surface of effects `jntx()`: Estimates how two exposures (heat and ozone, smoke and heat) act together on a count, as a surface of rate ratios over both, the effect of one at chosen levels of the other, and a test of the interaction. ```{r jntx} set.seed(10) d <- expand.grid(day = 1:150, city = 1:10) d$temp <- rnorm(nrow(d), 25, 4) d$o3 <- 0.6 * d$temp + rnorm(nrow(d), 30, 6) d$crimes <- rpois( nrow(d), exp(1 + 0.02 * d$temp + 0.001 * d$temp * d$o3 / 10) ) j <- jntx(d, "crimes", "temp", "o3", fe = "city") j plot(j) ``` ```{r jntx-plot} plot(j) ``` ## Exposure in bins: dose-response and tests of non-linearity `dosebin()`: Replaces a continuous exposure by indicators of its bins, the reference bin left out, fits the model, and tests whether the bins matter and whether their effects follow a straight line. ```{r dosebin} set.seed(11) d <- expand.grid(day = 1:100, area = 1:10) d$aqi <- rgamma(nrow(d), 4, 0.1) d$crimes <- rpois(nrow(d), exp(1 + 0.3 * (d$aqi > 50))) b <- dosebin(d, "crimes", "aqi", fe = c("area", "day")) b plot(b) ``` ```{r dosebin-plot} plot(b) ``` ## Effects by offence type in one call, with a multiple-testing correction `typefx()`: Fits the same model to several outcomes (assault, robbery, burglary, property crime, ...) and adjusts the p-values for the number of outcomes tested. ```{r typefx} set.seed(12) d <- expand.grid(day = 1:60, area = 1:12) d$pm <- rnorm(nrow(d), 20, 5) d$assault <- rpois(nrow(d), exp(0.5 + 0.03 * d$pm)) d$theft <- rpois(nrow(d), 2) r <- typefx(d, c("assault", "theft"), "pm", x = "pm", fe = c("area", "day")) r plot(r) ``` ```{r typefx-plot} plot(r) ``` ## Inverse-distance-weighted interpolation, and zonal means `idwint()`: Carries the values of monitors to target points as the mean of the nearest monitors weighted by their distance to the power `-p`, and averages the targets of each zone. Exposure papers assign monitor readings to places this way: Rahman et al. (2023, sec. 2.3) take "inverse distance squared weighting of observations from up to four nearby (<50 km) monitoring locations" for census tract centroids (`p = 2`, `k = 4`, `rad = 50`, `lonlat = TRUE`); Wongchanapai et al. (2025) interpolate a surface of annual PM2.5 "using the inverse distance weight method" and take "zonal statistics" per municipality (targets on a grid over the state, `zone` the municipality of each grid point; they used ArcGIS Pro and state neither the power nor the neighbours, so give both); Wesselbaum (2022) matches each crime "to the measures of the nearest weather, pollution station" (`k = 1`). ```{r idwint} m <- data.frame(x = c(0, 10, 0), y = c(0, 0, 10), pm = c(8, 12, 10)) idwint(m$x, m$y, m$pm, c(5, 0), c(0, 0)) # the nearest monitor only idwint(m$x, m$y, m$pm, c(9, 1), c(0, 1), k = 1) # a grid over two zones, and the zonal means g <- expand.grid(x = 0:10, y = 0:10) idwint(m$x, m$y, m$pm, g$x, g$y, zone = ifelse(g$x < 5, "west", "east")) ``` ## Geographically and temporally weighted regression `gtwreg()`: The regression of Kuo and Putra (2021, eqs 4-9), after Huang, Wu and Barry (2010): at each observation `i` the least-squares fit of all observations weighted by a Gaussian kernel of their space-time distance, so that the coefficients vary over places and periods. They relate robbery, domestic violence and fraud in the local government areas of New South Wales to the air quality index month by month. ```{r gtwreg} set.seed(4) d <- expand.grid(u = 1:6, v = 1:6, t = 1:4) d$aqi <- rnorm(nrow(d)) d$y <- 1 + (0.2 + 0.1 * d$u) * d$aqi + rnorm(nrow(d), 0, 0.3) r <- gtwreg(d$y, d["aqi"], d$u, d$v, d$t, h = c(1.5, 3, 6), tau = c(0, 1)) r r$grid ``` ## Association rules between two categorical variables `asrule()`: The rules the Apriori algorithm (Agrawal et al. 1996) finds when each observation holds one level of each of two variables: {} => {b} and {a} => {b} with `a` a level of one variable and `b` of the other, each with its support, confidence, coverage and lift. Wongchanapai et al. (2025) cut the rate of intimate partner violence and the annual PM2.5 of New Jersey's municipalities into five groups each with `cut()` and kept rules of "at least 10% support ... and at least 20% confidence" (`minsup = 0.1`, `minconf = 0.2`, the defaults here) in R's arules package; with two variables these are all its rules, the empty left-hand side included as arules includes it by default (`empty`). ```{r asrule} set.seed(5) pm <- cut(rnorm(200), 5, labels = c("vl", "l", "m", "mh", "vh")) ipv <- cut(rnorm(200), 5, labels = c("vl", "l", "m", "mh", "vh")) asrule(pm, ipv, nm = c("pm25", "ipv")) ``` ## Generalized synthetic control with interactive fixed effects `ifesc()`: The effect of a treatment adopted by some units of a balanced panel at possibly different times, estimated as the generalized synthetic control of Xu (2017): a model of the untreated outcome fitted to the units never treated, then carried to each treated unit through its periods before adoption. ```{r ifesc} set.seed(1) p <- expand.grid(id = 1:30, yr = 1:12) f <- cumsum(rnorm(12)) l <- rnorm(30) p$tr <- as.integer(p$id <= 6 & p$yr >= 9) p$y <- l[p$id] * f[p$yr] + 2 * p$tr + rnorm(nrow(p), 0, 0.3) r <- ifesc(p, "y", "tr", "id", "yr", r = 1, nboot = 50, seed = 1) r ``` ## Long-run effects from a common correlated effects fit `lrcce()`: The cross-sectionally augmented autoregressive distributed lag (CS-ARDL) long-run effects of Chudik et al. (2016) as Ditzen (2021, sec. 3.2) sets them out, from the unit estimates of `ccepnl()`. ```{r lrcce} set.seed(3) tt <- 30 d <- expand.grid(year = 1:tt, prov = paste0("p", 1:25)) f <- rnorm(tt)[d$year] g <- rnorm(25, 1)[as.integer(substring(d$prov, 2))] d$x <- g * f + rnorm(nrow(d)) d$xl <- ave(d$x, d$prov, FUN = function(v) c(NA, v[-length(v)])) d$y <- 0 for (i in which(d$year > 1)) { d$y[i] <- 0.4 * d$y[i - 1] + 0.5 * d$x[i] + 0.1 * d$xl[i] + g[i] * f[i] + rnorm(1) } k <- d$year > 1 # CS-ARDL: theta is 0.6 over 0.6, that is 1 r <- ccepnl(d$y[k], d[k, c("x", "xl")], d$prov[k], d$year[k], ylag = 1) lrcce(r, c("x", "xl")) # CS-DL: x and its first difference; the coefficient of x is theta d$dx <- d$x - d$xl ccepnl(d$y[k], d[k, c("x", "dx")], d$prov[k], d$year[k], lags = 3)$mg ``` ```{r lrcce-plot} plot(r) ``` ## Coarsened exact matching `cemtch()`: The matching of Iacus, King and Porro (2012): each covariate is coarsened into bins, the rows are grouped by their bins on every covariate at once, and only the groups (strata) holding both treated and control rows are kept, so that a later regression compares like with like without extrapolating. ```{r cemtch} set.seed(2) n <- 300 d <- data.frame(pov = rbinom(n, 1, 0.4), age = runif(n, 14, 18)) d$lead <- rbinom(n, 1, plogis(-1 + 1.5 * d$pov)) d$y <- 0.5 * d$lead + d$pov + 0.2 * d$age + rnorm(n) m <- cemtch(d, "lead", c("pov", "age"), cut = list(age = 4)) m stats::lm(y ~ lead, d, weights = m$w, subset = m$keep) ``` ## Least squares with regression diagnostics and predictions `olsdx()`: The multiple regression that Algahtany, Kumar and Barclay (2022) fit to monthly counts of each kind of offence in two regions, with the mean temperature, the mean relative humidity and the days of haze in the month as predictors, together with the checks they report before reading it: standardised coefficients, the tolerance and variance inflation of each predictor and the correlations among them, the Durbin-Watson statistic of the residuals, each row's leverage, studentised residuals and Cook's distance, and the expected count, with its standard error and interval, for a month of given weather. ```{r olsdx} # 84 months of weather and assaults, simulated set.seed(4) w <- data.frame(temp = rnorm(84, 26, 8), hum = runif(84, 10, 60), haze = rpois(84, 15)) assault <- 5 + 0.7 * w$temp + 0.15 * w$hum + 0.35 * w$haze + rnorm(84, sd = 4) r <- olsdx(assault, w, at = c(temp = 35, hum = 74, haze = 25)) r r$pred # one new month rather than the mean of such months olsdx(assault, w, at = c(temp = 35, hum = 74, haze = 25), pred = "new")$pred # a stricter count of influential rows print(r, cook = 4 / 84) ```