Skip to content

HDiagnostic accuracy · diagnostic.accuracy

Diagnostic accuracy (sensitivity, specificity, PPV, NPV)

How well does a yes/no test agree with the reference standard?

Cross-classifies a binary test against a reference standard and reports sensitivity, specificity, predictive values, accuracy, likelihood ratios, the diagnostic odds ratio, Youden's J, balanced accuracy, F1 and MCC with confidence intervals, plus predictive values at another prevalence.

Verified in Python and R Python and R agree to 10 decimals

A real result

Example “Liver scan”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Diagnostic accuracyRecorded · Python and R agreeRecorded 2026-11-17 · 43 values compared
R

sensitivity = .90, specificity = .63, LR+ = 2.41, LR− = 0.17

Sensitivity
0.8953
Specificity
0.6279
Positive predictive value
0.8783
Negative predictive value
0.6667

Effect size

  • Diagnostic odds ratio 14.438 95% CI [7.990, 26.089]
  • Youden's J 0.5233 95% CI [0.4145, 0.6320]

Plots

Confusion matrix: scan against pathologyHow often is each class predicted correctly, which errors does the model make, and what do sensitivity, specificity, precision and the other rates come to?

Positive: pathology = abnormal (reference) and scan = abnormal (test).

View data
Reference: pathologyCountTest: scan
Positive231Positive
Positive27Negative
Negative32Positive
Negative54Negative

Assumptions

  • No empty cells — Every cell has at least one subject.
  • Everyone verified by the reference — Rows missing either result were left out; if the reference was applied selectively, sensitivity and specificity are biased.

Test × reference

scan \ pathologyabnormal (condition)normal (no condition)Total
abnormal (positive)23132263
normal (negative)275481
Total25886344

Accuracy measures (95% CI; proportions Clopper–Pearson)

MeasureEstimateCI lowCI high
Sensitivity0.89530.85140.9299
Specificity0.62790.51700.7298
Positive predictive value0.87830.83260.9153
Negative predictive value0.66670.55320.7676
Accuracy0.82850.78440.8668
Prevalence (sample)0.75000.70080.7949
Likelihood ratio +2.4061.8233.176
Likelihood ratio −0.16670.11260.2467
Diagnostic odds ratio14.4387.99026.089
Youden's J0.52330.41450.6320
Balanced accuracy0.76160.70720.8160
F1 score0.8868——
Matthews correlation0.5340——
  • Positive test: scan = abnormal; condition present: pathology = abnormal. Likelihood-ratio intervals: Simel et al. (1991).
Python

sensitivity = .90, specificity = .63, LR+ = 2.41, LR− = 0.17

Sensitivity
0.8953
Specificity
0.6279
Positive predictive value
0.8783
Negative predictive value
0.6667

Effect size

  • Diagnostic odds ratio 14.438 95% CI [7.990, 26.089]
  • Youden's J 0.5233 95% CI [0.4145, 0.6320]

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • No empty cells — Every cell has at least one subject.
  • Everyone verified by the reference — Rows missing either result were left out; if the reference was applied selectively, sensitivity and specificity are biased.

Test × reference

scan \ pathologyabnormal (condition)normal (no condition)Total
abnormal (positive)23132263
normal (negative)275481
Total25886344

Accuracy measures (95% CI; proportions Clopper–Pearson)

MeasureEstimateCI lowCI high
Sensitivity0.89530.85140.9299
Specificity0.62790.51700.7298
Positive predictive value0.87830.83260.9153
Negative predictive value0.66670.55320.7676
Accuracy0.82850.78440.8668
Prevalence (sample)0.75000.70080.7949
Likelihood ratio +2.4061.8233.176
Likelihood ratio −0.16670.11260.2467
Diagnostic odds ratio14.4387.99026.089
Youden's J0.52330.41450.6320
Balanced accuracy0.76160.70720.8160
F1 score0.8868——
Matthews correlation0.5340——
  • Positive test: scan = abnormal; condition present: pathology = abnormal. Likelihood-ratio intervals: Simel et al. (1991).

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Liver scanliver_scan · reference: pathology · test: scan
  • Zero cell wilson prevalencerapid_test · reference: culture · test: rapid test
  • Pima jeffreyspima · reference: type · test: glu_high
  • Degenerate n1liver_scan · reference: pathology · test: scan

In the guides

Where it sits in the decision guides

  • Sensitivity, specificity, PPV, NPV · Statistics Guide · H — Diagnostic accuracy
  • Likelihood ratios, DOR, Youden J · Statistics Guide · H — Diagnostic accuracy
  • Compare to gold standard: McNemar (paired) · Statistics Guide · H — Diagnostic accuracy
  • Classical ML (trees, RF, GBM, SVM) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Test resultcategorical / boolean · 1 column · 2–2 levels
The index test's yes/no result.
Reference standardcategorical / boolean · 1 column · 2–2 levels
The true condition (gold standard).

Choices you make

hypothesis

Positive test leveldefault —

The test level meaning "positive" (default the last stored level — true for true/false columns).

Condition-present leveldefault —

The reference level meaning "condition present" (default the last stored level).

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

statistics

Interval for proportionsdefault clopper-pearson

Interval for sensitivity, specificity and predictive values. Clopper–Pearson is exact; Wilson is a little tighter.

  • Clopper–Pearson (exact)(default) — Inverts the exact binomial test; guarantees at least the stated coverage, so it runs wide.
  • Wilson score — Inverts the score test; good coverage at any sample size, so it's the usual choice.
  • Jeffreys — A Bayesian interval with a Jeffreys prior; coverage close to the stated level on average, and good at small n.
  • Agresti–Coull — Adds about two successes and two failures to the Wald interval; easy to compute, and sound except at very small n.
Predictive values at another prevalencedefault off

PPV and NPV in a population with a different prevalence (needed when cases and controls were sampled separately).

Population prevalencedefault 0.1

Share of the population with the condition. Predictive values depend on it strongly.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • No empty cells

    An empty cell makes the likelihood ratios undefined and needs a 0.5 correction for the diagnostic odds ratio.

  • Everyone verified by the reference

    Partial verification biases sensitivity and specificity.

What it reports

tp
Counts of predicted against actual classes. For two classes, these are TP, FP, FN and TN.
fp
Counts of predicted against actual classes. For two classes, these are TP, FP, FN and TN.
fn
Counts of predicted against actual classes. For two classes, these are TP, FP, FN and TN.
tn
Counts of predicted against actual classes. For two classes, these are TP, FP, FN and TN.
n
How many independent units the analysis used; it sets precision and power.
sensitivity
The share of real positives the test catches.
sensitivity_ci_low
A range of effect values compatible with your data at the chosen confidence level.
sensitivity_ci_high
A range of effect values compatible with your data at the chosen confidence level.
specificity
The share of real negatives the test correctly clears.
specificity_ci_low
A range of effect values compatible with your data at the chosen confidence level.
specificity_ci_high
A range of effect values compatible with your data at the chosen confidence level.
ppv
Of those who test positive, the share who really are; it falls sharply when the condition is rare.
ppv_ci_low
A range of effect values compatible with your data at the chosen confidence level.
ppv_ci_high
A range of effect values compatible with your data at the chosen confidence level.
npv
Of those who test negative, the share who really are negative.
npv_ci_low
A range of effect values compatible with your data at the chosen confidence level.
npv_ci_high
A range of effect values compatible with your data at the chosen confidence level.
accuracy
The share of predictions that are right; misleading when classes are imbalanced.
accuracy_ci_low
A range of effect values compatible with your data at the chosen confidence level.
accuracy_ci_high
A range of effect values compatible with your data at the chosen confidence level.
prevalence
How common the condition is in the population tested; it drives predictive values.
prevalence_ci_low
A range of effect values compatible with your data at the chosen confidence level.
prevalence_ci_high
A range of effect values compatible with your data at the chosen confidence level.
lr_pos
How much a positive (or negative) result multiplies the odds of the condition.
lr_pos_ci_low
A range of effect values compatible with your data at the chosen confidence level.
lr_pos_ci_high
A range of effect values compatible with your data at the chosen confidence level.
lr_neg
How much a positive (or negative) result multiplies the odds of the condition.
lr_neg_ci_low
A range of effect values compatible with your data at the chosen confidence level.
lr_neg_ci_high
A range of effect values compatible with your data at the chosen confidence level.
dor
The odds of a positive test in cases over the odds in non-cases, or LR+ divided by LR−.
dor_ci_low
A range of effect values compatible with your data at the chosen confidence level.
dor_ci_high
A range of effect values compatible with your data at the chosen confidence level.
dor_corrected
The odds of a positive test in cases over the odds in non-cases, or LR+ divided by LR−.
youden
Sensitivity + specificity − 1; the threshold that maximizes it weighs both errors equally.
youden_ci_low
A range of effect values compatible with your data at the chosen confidence level.
youden_ci_high
A range of effect values compatible with your data at the chosen confidence level.
balanced_accuracy
The average of recall across classes; 0.5 is chance for two classes, whatever the imbalance.
balanced_accuracy_ci_low
A range of effect values compatible with your data at the chosen confidence level.
balanced_accuracy_ci_high
A range of effect values compatible with your data at the chosen confidence level.
f1
Precision — of predicted positives, how many are right; recall — of real positives, how many were found.
mcc
The correlation between a binary prediction and the truth, using all four cells of the table. 0 means no better than chance.
test_positive
Level of the test column that counts as a positive result (by default its last level).
reference_positive
Level of the reference column that means the condition is present (by default its last level).

Per group, level or term: ppv_adj, ppv_adj_ci_low, ppv_adj_ci_high, npv_adj, npv_adj_ci_low, npv_adj_ci_high (prevalence adjustment), npv_adj, ppv_adj

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Clopper–Pearson and Jeffreys limits are beta quantiles: Boost (scipy) and R's qbeta agree to ≈1e-12.
Python

The exact script CodeSplash ran for example “Liver scan” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Diagnostic accuracy (sensitivity, specificity, PPV, NPV)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.accuracy 1.0.2 · spec ccb26f33bffe0a0b
# Dataset: liver_scan (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import diagnostic as csd  # every accuracy measure (twin of codesplashr::cs_diag_accuracy)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/liver_scan.parquet", columns=["scan", "pathology"])
n_input = len(df)
df["scan"] = pd.Categorical(df["scan"], categories=["normal", "abnormal"])  # stored level order
df["pathology"] = pd.Categorical(df["pathology"], categories=["normal", "abnormal"])  # stored level order
df = df.dropna(subset=["scan", "pathology"])  # listwise deletion over the analysis columns
df["scan"] = df["scan"].cat.remove_unused_categories()
df["pathology"] = df["pathology"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["scan", "pathology"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
t, r = "scan", "pathology"
test_levels = ["normal", "abnormal"]  # stored level order
ref_levels = ["normal", "abnormal"]
test_pos = test_levels[-1]  # default: the last level ("true")
ref_pos = ref_levels[-1]  # condition-present level
test_neg = next(lv for lv in test_levels if lv != test_pos)
ref_neg = next(lv for lv in ref_levels if lv != ref_pos)
tp_ = df[t].astype(str) == test_pos
dp_ = df[r].astype(str) == ref_pos
tp, fp = int((tp_ & dp_).sum()), int((tp_ & ~dp_).sum())
fn, tn = int((~tp_ & dp_).sum()), int((~tp_ & ~dp_).sum())
# Sensitivity and specificity need rows with and without the condition.
k_ref = int(tp + fn > 0) + int(fp + tn > 0)
if k_ref < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=r, min=2, k=k_ref)
conf = 0.95
ci_method = "clopper-pearson"
prevalence = None  # population prevalence (optional)

acc = csd.accuracy(tp, fp, fn, tn, conf=conf, ci_method=ci_method, prevalence=prevalence)

# %% Assumptions
zero = [name for name, x in (("true positive", tp), ("false positive", fp), ("false negative", fn), ("true negative", tn)) if x == 0]
assumptions = [
    {"key": "cells", "label": "No empty cells", "status": "warn" if zero else "pass",
     "detail": ("Empty " + " and ".join(zero) + " cell: likelihood ratios can be infinite or undefined; 0.5 was added to every cell for the DOR.") if zero else "Every cell has at least one subject."},
    {"key": "verification", "label": "Everyone verified by the reference", "status": "info",
     "detail": "Rows missing either result were left out; if the reference was applied selectively, sensitivity and specificity are biased."},
]

# %% Result
ci_label = {"clopper-pearson": "Clopper–Pearson", "wilson": "Wilson", "jeffreys": "Jeffreys", "agresti-coull": "Agresti–Coull"}[ci_method]
measures = [
    ("sensitivity", "Sensitivity"), ("specificity", "Specificity"), ("ppv", "Positive predictive value"), ("npv", "Negative predictive value"),
    ("accuracy", "Accuracy"), ("prevalence", "Prevalence (sample)"), ("lr_pos", "Likelihood ratio +"), ("lr_neg", "Likelihood ratio −"),
    ("dor", "Diagnostic odds ratio"), ("youden", "Youden's J"), ("balanced_accuracy", "Balanced accuracy"),
]
if prevalence is not None:
    measures += [("ppv_adj", f"PPV at prevalence {prevalence:g}"), ("npv_adj", f"NPV at prevalence {prevalence:g}")]
rows = [{"measure": label, "estimate": acc[k], "ci_low": acc.get(f"{k}_ci_low"), "ci_high": acc.get(f"{k}_ci_high")} for k, label in measures]
rows += [{"measure": "F1 score", "estimate": acc["f1"], "ci_low": None, "ci_high": None},
         {"measure": "Matthews correlation", "estimate": acc["mcc"], "ci_low": None, "ci_high": None}]
summary = (
    f"Sensitivity {acc['sensitivity']:.1%} ({tp}/{tp + fn}), specificity {acc['specificity']:.1%} ({tn}/{tn + fp}), "
    f"PPV {acc['ppv']:.1%}, NPV {acc['npv']:.1%}; LR+ {cs.fmt_num(acc['lr_pos'])}, LR− {cs.fmt_num(acc['lr_neg'])}."
)
values = {k: v for k, v in acc.items()}
values.update({"test_positive": test_pos, "reference_positive": ref_pos})
cs.publish({
    "method": "diagnostic.accuracy",
    "methodVersion": "1.0.2",
    "title": "Diagnostic accuracy",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": tp + fp + fn + tn,
    "summary": summary,
    "apa": f"sensitivity = {cs.fmt_num(acc['sensitivity'], leading_zero=False)}, specificity = {cs.fmt_num(acc['specificity'], leading_zero=False)}, "
           f"LR+ = {cs.fmt_num(acc['lr_pos'])}, LR− = {cs.fmt_num(acc['lr_neg'])}",
    "statistics": [{"key": k, "label": label, "value": acc[k]} for k, label in measures[:4]],
    "tables": [
        {"key": "confusion", "title": "Test × reference",
         "columns": [{"key": "row", "label": f"{t} \\ {r}", "type": "string"}, {"key": "pos", "label": f"{ref_pos} (condition)", "type": "integer"},
                     {"key": "neg", "label": f"{ref_neg} (no condition)", "type": "integer"}, {"key": "total", "label": "Total", "type": "integer"}],
         "rows": [{"row": f"{test_pos} (positive)", "pos": tp, "neg": fp, "total": tp + fp},
                  {"row": f"{test_neg} (negative)", "pos": fn, "neg": tn, "total": fn + tn},
                  {"row": "Total", "pos": tp + fn, "neg": fp + tn, "total": tp + fp + fn + tn}]},
        {"key": "measures", "title": f"Accuracy measures ({conf:.0%} CI; proportions {ci_label})",
         "columns": [{"key": "measure", "label": "Measure", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
                     {"key": "ci_low", "label": "CI low", "type": "number"}, {"key": "ci_high", "label": "CI high", "type": "number"}],
         "rows": rows},
    ],
    "effectSizes": [
        {"key": "dor", "label": "Diagnostic odds ratio", "value": acc["dor"], "ciLow": acc["dor_ci_low"], "ciHigh": acc["dor_ci_high"], "ciLevel": conf,
         "method": "Woolf log interval" + (" (0.5 added to every cell)" if acc["dor_corrected"] else "")},
        {"key": "youden", "label": "Youden's J", "value": acc["youden"], "ciLow": acc["youden_ci_low"], "ciHigh": acc["youden_ci_high"], "ciLevel": conf,
         "method": "Se + Sp − 1, Wald interval"},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Positive test: {t} = {test_pos}; condition present: {r} = {ref_pos}. Likelihood-ratio intervals: Simel et al. (1991)."
              + (f" Prevalence-adjusted predictive values: Mercaldo et al. (2007) logit intervals." if prevalence is not None else "")],
    # Chart Lab `confusion-matrix`: reference in rows, test in columns, condition-present first (TP top left).
    # Its intervals are Wilson intervals, so they show only when the method's own interval is Wilson too.
    "charts": [cs.chart(
        "confusion", "confusion-matrix", f"Confusion matrix: {t} against {r}",
        {"actual": cs.col(f"Reference: {r}", ["Positive", "Positive", "Negative", "Negative"], levels=["Positive", "Negative"]),
         "predicted": cs.col(f"Test: {t}", ["Positive", "Negative", "Positive", "Negative"], levels=["Positive", "Negative"]),
         "count": cs.col("Count", [tp, fn, fp, tn], kind="numeric")},
        controls={"positive": "first", "view": "compact", "intervals": ci_method == "wilson"},
        note=f"Positive: {r} = {ref_pos} (reference) and {t} = {test_pos} (test).",
    )],
    "values": values,
})
R

The exact script CodeSplash ran for example “Liver scan” · R version 4.5.1 (2025-06-13)

# Diagnostic accuracy (sensitivity, specificity, PPV, NPV)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.accuracy 1.0.2 · spec ccb26f33bffe0a0b
# Dataset: liver_scan (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_diag_accuracy (twin of codesplash.stats.diagnostic)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/liver_scan.parquet", col_select = c("scan", "pathology")))
n_input <- nrow(df)
df[["scan"]] <- factor(df[["scan"]], levels = c("normal", "abnormal"))  # stored level order
df[["pathology"]] <- factor(df[["pathology"]], levels = c("normal", "abnormal"))  # stored level order
df <- df[stats::complete.cases(df[c("scan", "pathology")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("scan", "pathology"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
t <- "scan"
r <- "pathology"
test_levels <- c("normal", "abnormal")  # stored level order
ref_levels <- c("normal", "abnormal")
test_pos <- test_levels[length(test_levels)]  # default: the last level ("true")
ref_pos <- ref_levels[length(ref_levels)]  # condition-present level
test_neg <- setdiff(test_levels, test_pos)[1]
ref_neg <- setdiff(ref_levels, ref_pos)[1]
is_tp <- as.character(df[[t]]) == test_pos
is_dp <- as.character(df[[r]]) == ref_pos
tp <- sum(is_tp & is_dp)
fp <- sum(is_tp & !is_dp)
fn <- sum(!is_tp & is_dp)
tn <- sum(!is_tp & !is_dp)
# Sensitivity and specificity need rows with and without the condition.
k_ref <- (tp + fn > 0) + (fp + tn > 0)
if (k_ref < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = r, min = 2, k = k_ref)
conf <- 0.95
ci_method <- "clopper-pearson"
prevalence <- NULL  # population prevalence (optional)

acc <- cs_diag_accuracy(tp, fp, fn, tn, conf = conf, ci_method = ci_method, prevalence = prevalence)

# %% Assumptions
cell_names <- c("true positive", "false positive", "false negative", "true negative")
zero <- cell_names[c(tp, fp, fn, tn) == 0]
assumptions <- list(
  list(key = "cells", label = "No empty cells", status = if (length(zero)) "warn" else "pass",
       detail = if (length(zero)) paste0("Empty ", paste(zero, collapse = " and "), " cell: likelihood ratios can be infinite or undefined; 0.5 was added to every cell for the DOR.") else "Every cell has at least one subject."),
  list(key = "verification", label = "Everyone verified by the reference", status = "info",
       detail = "Rows missing either result were left out; if the reference was applied selectively, sensitivity and specificity are biased.")
)

# %% Result
ci_label <- c("clopper-pearson" = "Clopper–Pearson", wilson = "Wilson", jeffreys = "Jeffreys", "agresti-coull" = "Agresti–Coull")[[ci_method]]
measures <- list(
  c("sensitivity", "Sensitivity"), c("specificity", "Specificity"), c("ppv", "Positive predictive value"), c("npv", "Negative predictive value"),
  c("accuracy", "Accuracy"), c("prevalence", "Prevalence (sample)"), c("lr_pos", "Likelihood ratio +"), c("lr_neg", "Likelihood ratio −"),
  c("dor", "Diagnostic odds ratio"), c("youden", "Youden's J"), c("balanced_accuracy", "Balanced accuracy")
)
if (!is.null(prevalence)) {
  measures <- c(measures, list(c("ppv_adj", sprintf("PPV at prevalence %s", format(prevalence))), c("npv_adj", sprintf("NPV at prevalence %s", format(prevalence)))))
}
rows <- lapply(measures, function(m) list(measure = m[2], estimate = acc[[m[1]]], ci_low = acc[[paste0(m[1], "_ci_low")]], ci_high = acc[[paste0(m[1], "_ci_high")]]))
rows <- c(rows, list(list(measure = "F1 score", estimate = acc$f1, ci_low = NULL, ci_high = NULL),
                     list(measure = "Matthews correlation", estimate = acc$mcc, ci_low = NULL, ci_high = NULL)))
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf("Sensitivity %.1f%% (%d/%d), specificity %.1f%% (%d/%d), PPV %.1f%%, NPV %.1f%%; LR+ %s, LR− %s.",
                   100 * acc$sensitivity, tp, tp + fn, 100 * acc$specificity, tn, tn + fp, 100 * acc$ppv, 100 * acc$npv,
                   cs_fmt_num(acc$lr_pos), cs_fmt_num(acc$lr_neg))
values <- acc
values$test_positive <- test_pos
values$reference_positive <- ref_pos
cs_publish(list(
  method = "diagnostic.accuracy",
  methodVersion = "1.0.2",
  title = "Diagnostic accuracy",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = tp + fp + fn + tn,
  summary = summary,
  apa = sprintf("sensitivity = %s, specificity = %s, LR+ = %s, LR− = %s", cs_fmt_num(acc$sensitivity, leading_zero = FALSE),
                cs_fmt_num(acc$specificity, leading_zero = FALSE), cs_fmt_num(acc$lr_pos), cs_fmt_num(acc$lr_neg)),
  statistics = lapply(measures[1:4], function(m) list(key = m[1], label = m[2], value = acc[[m[1]]])),
  tables = list(
    list(key = "confusion", title = "Test × reference",
         columns = list(list(key = "row", label = paste(t, "\\", r), type = "string"), list(key = "pos", label = paste(ref_pos, "(condition)"), type = "integer"),
                        list(key = "neg", label = paste(ref_neg, "(no condition)"), type = "integer"), list(key = "total", label = "Total", type = "integer")),
         rows = list(list(row = paste(test_pos, "(positive)"), pos = tp, neg = fp, total = tp + fp),
                     list(row = paste(test_neg, "(negative)"), pos = fn, neg = tn, total = fn + tn),
                     list(row = "Total", pos = tp + fn, neg = fp + tn, total = tp + fp + fn + tn))),
    list(key = "measures", title = sprintf("Accuracy measures (%s CI; proportions %s)", pct, ci_label),
         columns = list(list(key = "measure", label = "Measure", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
                        list(key = "ci_low", label = "CI low", type = "number"), list(key = "ci_high", label = "CI high", type = "number")),
         rows = rows)
  ),
  effectSizes = list(
    list(key = "dor", label = "Diagnostic odds ratio", value = acc$dor, ciLow = acc$dor_ci_low, ciHigh = acc$dor_ci_high, ciLevel = conf,
         method = paste0("Woolf log interval", if (acc$dor_corrected == 1) " (0.5 added to every cell)" else "")),
    list(key = "youden", label = "Youden's J", value = acc$youden, ciLow = acc$youden_ci_low, ciHigh = acc$youden_ci_high, ciLevel = conf,
         method = "Se + Sp − 1, Wald interval")
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(sprintf("Positive test: %s = %s; condition present: %s = %s. Likelihood-ratio intervals: Simel et al. (1991).", t, test_pos, r, ref_pos),
                      if (!is.null(prevalence)) " Prevalence-adjusted predictive values: Mercaldo et al. (2007) logit intervals." else "")),
  # Chart Lab `confusion-matrix`: reference in rows, test in columns, condition-present first (TP top left).
  # Its intervals are Wilson intervals, so they show only when the method's own interval is Wilson too.
  charts = list(cs_chart(
    "confusion", "confusion-matrix", sprintf("Confusion matrix: %s against %s", t, r),
    list(actual = cs_col(paste0("Reference: ", r), c("Positive", "Positive", "Negative", "Negative"), levels = c("Positive", "Negative")),
         predicted = cs_col(paste0("Test: ", t), c("Positive", "Negative", "Positive", "Negative"), levels = c("Positive", "Negative")),
         count = cs_col("Count", as.numeric(c(tp, fn, fp, tn)), kind = "numeric")),
    controls = list(positive = "first", view = "compact", intervals = identical(ci_method, "wilson")),
    note = sprintf("Positive: %s = %s (reference) and %s = %s (test).", r, ref_pos, t, test_pos)
  )),
  values = values
))

Sources

  • Altman, D. G., & Bland, J. M. (1994). Diagnostic tests 1: sensitivity and specificity. BMJ, 308, 1552.
  • Simel, D. L., Samsa, G. P., & Matchar, D. B. (1991). Likelihood ratios with confidence: sample size estimation for diagnostic test studies. Journal of Clinical Epidemiology, 44, 763–770.
  • Mercaldo, N. D., Lau, K. F., & Zhou, X. H. (2007). Confidence intervals for predictive values with an emphasis to case–control studies. Statistics in Medicine, 26, 2170–2183.
  • Glas, A. S., Lijmer, J. G., Prins, M. H., Bonsel, G. J., & Bossuyt, P. M. M. (2003). The diagnostic odds ratio. Journal of Clinical Epidemiology, 56, 1129–1135.

From the CodeSplash method registry · diagnostic.accuracy v1.0.2.