Example: estimating the distribution of a scan statistic by simulation

example
scan statistics
R
A sample post showing what the blog supports: formulas, R code, tables, numbered statements. It can be deleted or replaced.
Author

Alexandru Amărioarei

Published

November 20, 2026

NoteThis is a sample post

It shows what a post on this blog looks like: text, LaTeX formulas, R code, a table and a numbered statement. To write a new post, copy this folder, change the date and title, and rewrite the text. The post can be deleted at any time (the folder blog/posts/2026-11-20-exemplu/ and its Romanian counterpart in ro/blog/posts/).

The problem

Let \(X_1, X_2, \dots, X_N\) be independent Bernoulli random variables with parameter \(p\). For a window of length \(m\), the one-dimensional discrete scan statistic is

\[ S_m(N) = \max_{1 \le i \le N-m+1} \; \sum_{k=i}^{i+m-1} X_k . \]

We are interested in \(\mathbb{P}\big(S_m(N) \ge k\big)\), the probability that somewhere in the sequence a window of length \(m\) contains at least \(k\) successes.

Definition 1 (Scan statistic) For a sequence \((X_k)\) and a length \(m\), the scan statistic is the largest number of successes contained in a window of \(m\) consecutive observations.

Monte Carlo estimation in R

The simplest estimator is the relative frequency over a large number of independent simulations:

\[ \widehat{P}_n = \frac{1}{n} \sum_{r=1}^{n} \mathbf{1}\{S^{(r)}_m(N) \ge k\}, \qquad \operatorname{se}\big(\widehat{P}_n\big) \approx \sqrt{\frac{\widehat{P}_n (1-\widehat{P}_n)}{n}} . \]

scan_1d <- function(x, m) {
  # window sums of length m, computed from cumulative sums
  s <- cumsum(c(0, x))
  max(s[(m + 1):length(s)] - s[1:(length(s) - m)])
}

set.seed(2026)
N <- 1000; m <- 20; p <- 0.05; k <- 6
S <- replicate(10000, scan_1d(rbinom(N, 1, p), m))

p_hat <- mean(S >= k)
se    <- sqrt(p_hat * (1 - p_hat) / length(S))
c(estimate = p_hat, std_error = se)

The block above is only displayed. To have R run the code when the site is rendered and include its output (figures too), write the block as ```{r}. The results are stored in _freeze/, so the site can be rebuilt without R.

What else a post can contain

Element Quarto syntax
Formula $...$ and $$...$$
Theorem ::: {#thm-name} ... :::
Figure ![Caption](figure.png)
R / Python code ```{r} / ```{python}
Footnote text[^1]

Cross-references work automatically: for example, Definition 1 above.

Back to top