Skip to content

EGenetics · genetics.setassoc

Rare-variant set tests (SKAT, SKAT-O, burden)

Is a set of rare variants in a gene, taken together, associated with the trait?

Pools the variants of one gene or region because each is too rare to test alone. The burden test adds them up and is strongest when effects share a direction; SKAT asks whether any variant's effect is non-zero, in either direction; SKAT-O searches between the two and pays for the search in its p-value. Variants are weighted by a Beta(1, 25) density of their minor-allele frequency, the trait is adjusted for covariates, and p-values come from the exact chi-square mixture, not a χ² with one df per variant. Research use only.

Experimental Python and R agree to 6 decimals Also called SKAT, SKAT-O, SKAT O…

A real result

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

SKATRecorded · Python and R agreeRecorded 2026-11-17 · 28 values compared · largest relative difference 6.6e-16
R

SKAT, 12 variants, N = 200, p = .366

Variants tested
12
Cumulative minor-allele count
379
Q
4173.72
p (SKAT)
.366

Assumptions

  • Correct null model — Linear null model with 1 covariate.
  • Unrelated people — Not checkable here: relatives would need a kinship model.
  • Weights and set fixed in advance — Beta(MAF; 1, 25) weights on 12 variants.
  • Enough cases (binary traits) — A continuous trait: not applicable.

SKAT, burden and SKAT-O

TestQp
SKAT (ρ = 0)4173.720.3655
Weighted burden (ρ = 1)260.740.7892
SKAT-O (min over ρ, adjusted)—0.5539

SKAT-O grid

ρQ_ρp_ρ (unadjusted)
04173.720.3655
0.01004134.590.3716
0.04004017.200.3899
0.09003821.550.4206
0.25003195.470.5123
0.50002217.230.6298
1264.650.7889

Variants in the set

VariantAllele countedMAFMinor-allele countRecoded to minorWeight
v01B0.0050222.166
v02B0.0200815.395
v03B0.02501013.616
v04B0.0425178.816
v05B0.0725294.107
v06B0.0600245.663
v07B0.0675274.672
v08B0.1075431.631
v09B0.1175471.245
v10B0.1275510.9469
v11B0.1450580.5823
v12B0.1575630.4089
  • Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
  • Q follows a mixture of 1-df chi-squares (eigenvalues of the weighted score covariance); a χ² with one df per variant would be wrong.
  • SKAT-O's smallest grid p was 0.3655 at ρ = 0; the SKAT-O p-value accounts for searching the grid, so it is larger.
Python

SKAT, 12 variants, N = 200, p = .366

Variants tested
12
Cumulative minor-allele count
379
Q
4173.72
p (SKAT)
.366

Assumptions

  • Correct null model — Linear null model with 1 covariate.
  • Unrelated people — Not checkable here: relatives would need a kinship model.
  • Weights and set fixed in advance — Beta(MAF; 1, 25) weights on 12 variants.
  • Enough cases (binary traits) — A continuous trait: not applicable.

SKAT, burden and SKAT-O

TestQp
SKAT (ρ = 0)4173.720.3655
Weighted burden (ρ = 1)260.740.7892
SKAT-O (min over ρ, adjusted)—0.5539

SKAT-O grid

ρQ_ρp_ρ (unadjusted)
04173.720.3655
0.01004134.590.3716
0.04004017.200.3899
0.09003821.550.4206
0.25003195.470.5123
0.50002217.230.6298
1264.650.7889

Variants in the set

VariantAllele countedMAFMinor-allele countRecoded to minorWeight
v01B0.0050222.166
v02B0.0200815.395
v03B0.02501013.616
v04B0.0425178.816
v05B0.0725294.107
v06B0.0600245.663
v07B0.0675274.672
v08B0.1075431.631
v09B0.1175471.245
v10B0.1275510.9469
v11B0.1450580.5823
v12B0.1575630.4089
  • Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
  • Q follows a mixture of 1-df chi-squares (eigenvalues of the weighted score covariance); a χ² with one df per variant would be wrong.
  • SKAT-O's smallest grid p was 0.3655 at ρ = 0; the SKAT-O p-value accounts for searching the grid, so it is larger.

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Guide skatge_skat_guide · covariates: age · outcome: y · variants: v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12
  • Guide skatoge_skat_guide · covariates: age · outcome: y · variants: v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12
  • Guide burdenge_skat_guide · covariates: age · outcome: y · variants: v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12
  • Guide skato evenge_skat_guide · covariates: age · outcome: y · variants: v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12
  • People bmi skatoge_people · covariates: age, sex · outcome: bmi · variants: r01, r02, r03, r04, r05, r06, r07, r08, r09, r10, r11, r12, r13, r14, r15
  • People bmi skat nocovge_people · outcome: bmi · variants: r01, r02, r03, r04, r05, r06, r07, r08, r09, r10, r11, r12, r13, r14, r15
  • People case skatge_people · covariates: age · outcome: case · variants: r01, r02, r03, r04, r05, r06, r07, r08, r09, r10, r11, r12, r13, r14, r15
  • People case burden flatge_people · covariates: age · outcome: case · variants: r01, r02, r03, r04, r05, r06, r07, r08

In the guides

Tests from the statistics guide this method runs

What you need

Traitnumeric / boolean · 1 column
One row per person: a measured trait, or 0/1 for case status.
Covariates (optional)numeric / categorical / boolean · 0–20 columns
Adjusted for in the null model: age, sex, principal components of ancestry.
Variants in the setnumeric / categorical · 1–2000 columns
One column per variant: doses 0/1/2, VCF calls (0/1, 1|1, ./.) or two alleles. No-calls are filled with the mean.

Choices you make

hypothesis

Testdefault skato

Choose before looking. SKAT-O is the safe default when you don't know whether effects share a direction.

  • SKAT-O(default) — Searches between SKAT and burden over a grid of ρ and adjusts the p-value for the search.
  • SKAT — Variance-component test: any non-zero effects, in either direction. ρ = 0.
  • Weighted burden — Adds weighted minor-allele counts into one score; best when effects share a direction. ρ = 1.
Trait typedefault auto

Linear null model for a measured trait, logistic for 0/1; automatic picks logistic when the trait holds only 0 and 1.

  • Automatic(default) — Logistic when the trait holds only 0 and 1, otherwise linear.
  • Continuous — Linear null model; residual variance estimated with n − p degrees of freedom.
  • Binary (0/1) — Logistic null model; asymptotic p-values without a small-sample correction.

statistics

Variant weightsdefault beta

Weights decide which variants count most. Fix them before looking at the results.

  • Beta density of the MAF(default) — Beta(MAF; a, b): with a = 1, b = 25 rarer variants get much larger weights (Wu et al. 2011).
  • Equal weights — Every variant counts the same, whatever its frequency.
Beta weight adefault 1

First shape of the Beta weight; 1 is the usual choice.

Beta weight bdefault 25

Second shape; 25 up-weights rare variants, 1 with a = 1 gives equal weights.

ρ griddefault adj

Values of ρ that SKAT-O searches; the p-value accounts for the search either way.

  • 0, 0.01, 0.04, 0.09, 0.25, 0.5, 1(default) — Denser near SKAT (Lee et al. 2012, the optimal.adj grid).
  • 0, 0.1, …, 1 — Eleven evenly spaced values.
Most no-calls per variantdefault 0.15

Variants with a larger share of no-calls are left out; the rest have no-calls filled with the mean dose.

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.

  • Correct null model

    The trait model with covariates must fit: ancestry and other confounders belong in it.

  • Unrelated people

    Relatives share variants and trait values, which inflates the test unless modeled.

  • Weights and set fixed in advance

    Choosing weights, variants or ρ after seeing results invalidates the p-value.

  • Enough cases (binary traits)

    Asymptotic p-values can be anti-conservative with few cases or very rare variants.

What it reports

  • Tests: No variant in the set is associated with the trait
n
Asks whether variant effects vary around zero, without assuming a direction. Its statistic Q follows a weighted sum of 1-df chi-squares.
n_variants_input
How much each variant counts in a set test. The Beta(MAF; 1, 25) density gives the rarest variants the most weight.
n_variants
How much each variant counts in a set test. The Beta(MAF; 1, 25) density gives the rarest variants the most weight.
n_dropped_missing
How much each variant counts in a set test. The Beta(MAF; 1, 25) density gives the rarest variants the most weight.
n_monomorphic
How much each variant counts in a set test. The Beta(MAF; 1, 25) density gives the rarest variants the most weight.
n_flipped
How much each variant counts in a set test. The Beta(MAF; 1, 25) density gives the rarest variants the most weight.
cmac
How much each variant counts in a set test. The Beta(MAF; 1, 25) density gives the rarest variants the most weight.
outcome_type
Asks whether variant effects vary around zero, without assuming a direction. Its statistic Q follows a weighted sum of 1-df chi-squares.
test
Asks whether variant effects vary around zero, without assuming a direction. Its statistic Q follows a weighted sum of 1-df chi-squares.
test_label
Asks whether variant effects vary around zero, without assuming a direction. Its statistic Q follows a weighted sum of 1-df chi-squares.
p
Asks whether variant effects vary around zero, without assuming a direction. Its statistic Q follows a weighted sum of 1-df chi-squares.
q
Asks whether variant effects vary around zero, without assuming a direction. Its statistic Q follows a weighted sum of 1-df chi-squares.
p_skat
Asks whether variant effects vary around zero, without assuming a direction. Its statistic Q follows a weighted sum of 1-df chi-squares.
q_skat
Asks whether variant effects vary around zero, without assuming a direction. Its statistic Q follows a weighted sum of 1-df chi-squares.
p_skat_liu
Asks whether variant effects vary around zero, without assuming a direction. Its statistic Q follows a weighted sum of 1-df chi-squares.
p_skat_method
Asks whether variant effects vary around zero, without assuming a direction. Its statistic Q follows a weighted sum of 1-df chi-squares.
p_burden
SKAT-O tries several mixes ρ of SKAT (0) and burden (1) and keeps the smallest p, then corrects for having searched.
q_burden
SKAT-O tries several mixes ρ of SKAT (0) and burden (1) and keeps the smallest p, then corrects for having searched.
p_skato
SKAT-O tries several mixes ρ of SKAT (0) and burden (1) and keeps the smallest p, then corrects for having searched.
p_min
SKAT-O tries several mixes ρ of SKAT (0) and burden (1) and keeps the smallest p, then corrects for having searched.
rho_best
SKAT-O tries several mixes ρ of SKAT (0) and burden (1) and keeps the smallest p, then corrects for having searched.
rho
SKAT-O tries several mixes ρ of SKAT (0) and burden (1) and keeps the smallest p, then corrects for having searched.
p_rho
SKAT-O tries several mixes ρ of SKAT (0) and burden (1) and keeps the smallest p, then corrects for having searched.
q_rho
SKAT-O tries several mixes ρ of SKAT (0) and burden (1) and keeps the smallest p, then corrects for having searched.
maf
How much each variant counts in a set test. The Beta(MAF; 1, 25) density gives the rarest variants the most weight.
weight
How much each variant counts in a set test. The Beta(MAF; 1, 25) density gives the rarest variants the most weight.
s2
Asks whether variant effects vary around zero, without assuming a direction. Its statistic Q follows a weighted sum of 1-df chi-squares.
n_covariates
Asks whether variant effects vary around zero, without assuming a direction. Its statistic Q follows a weighted sum of 1-df chi-squares.

Python and R

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

Default traps between the two languages

  • Mixture tails by Imhof's integral (QUADPACK in both engines) instead of SKAT's Davies algorithm (accuracy 1e-6): p-values agree with SKAT within about 1e-6, and SKAT-O within the 1e-4 relative tolerance of SKAT's own integration. When one eigenvalue dwarfs the rest (the burden end of the grid) the largest term is conditioned on, so the tail stays exact.
  • SKAT-O evaluates the burden end of the grid at ρ = 0.999, as SKAT does, because its integral divides by 1 − ρ.
  • Binary traits use the asymptotic null (SKAT_Null_Model(..., Adjustment = FALSE)); SKAT's small-sample kurtosis adjustment for n < 2000 resamples with R's generator and isn't reproduced.
Python

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

# Rare-variant set tests (SKAT, SKAT-O, burden)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.setassoc 1.0.1 · spec 957a7d911cb9faab
# Dataset: ge_skat_guide (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 genetics as gen  # genotype parsing, design matrix (twins of cs_gen_*)
from codesplash.stats import genetics_skat as skat  # SKAT, burden, SKAT-O (Wu et al. 2011; Lee et al. 2012; twins of cs_skat_*)

# %% Data (no rows dropped here: genotype no-calls and missing values are handled by the analysis)
df = pd.read_parquet("tests/parity/fixtures/ge_skat_guide.parquet", columns=["y", "age", "v01", "v02", "v03", "v04", "v05", "v06", "v07", "v08", "v09", "v10", "v11", "v12"])
n_input = len(df)
warnings = []
research_note = "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."

# %% People: trait and covariates (people missing either are left out; genotype no-calls stay)
outcome = "y"
covariates = ["age"]
variants = ["v01", "v02", "v03", "v04", "v05", "v06", "v07", "v08", "v09", "v10", "v11", "v12"]
kinds = {"age":"numeric","v01":"numeric","v02":"numeric","v03":"numeric","v04":"numeric","v05":"numeric","v06":"numeric","v07":"numeric","v08":"numeric","v09":"numeric","v10":"numeric","v11":"numeric","v12":"numeric","y":"numeric"}
keep = df[[outcome] + covariates].notna().all(axis=1).to_numpy()
n_left = int((~keep).sum())
if n_left:
    warnings.append(f"{n_left} of {n_input} people were left out because the trait or a covariate was missing.")
df = df[keep].reset_index(drop=True)
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, [outcome] + covariates)  # infinite values stop the run (registry/errors.yaml)
y = df[outcome].astype(float).to_numpy()
x, x_names = gen.design({c: df[c].to_numpy() for c in covariates}, kinds, len(y))
# Each test fits the covariates and one marker and needs at least one residual degree of freedom.
if len(y) < x.shape[1] + 2:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="The association test", min=x.shape[1] + 2, n=len(y))
if np.all(y == y[0]):
    cs.cs_error("CS_E_CONSTANT", column=outcome)
outcome_type = "auto"
is01 = bool(np.all((y == 0) | (y == 1))) and len(np.unique(y)) == 2
if outcome_type == "auto":
    outcome_type = "binary" if is01 else "continuous"
if outcome_type == "binary" and not is01:
    raise ValueError(f"A binary trait must hold only 0 and 1, with both present; {outcome} doesn't.")
binary = outcome_type == "binary"
g, counted, other = gen.dose_matrix({v: df[v].to_numpy() for v in variants})
test = "skat"
weights = "beta"
beta_a, beta_b = float(1), float(25)
rho_grid = skat.RHO_ADJ if "adj" == "adj" else skat.RHO_EVEN
max_missing = float(0.15)

# %% Variants: minor-allele coding, no-calls filled with the mean, weights
prep = skat.prepare(g, max_missing, beta_a, beta_b, weights)
kept = [v for v, k in zip(variants, prep["keep"]) if k]
if not kept:
    cs.cs_error("CS_E_UNDEFINED", what="The set test", reason="every variant is monomorphic here or has too many no-calls")
if prep["n_dropped_missing"]:
    warnings.append(f"{prep['n_dropped_missing']} variants had more than {max_missing:.0%} no-calls and were left out.")
if prep["n_monomorphic"]:
    warnings.append(f"{prep['n_monomorphic']} variants are monomorphic in these people and were left out.")
n_fill = int(np.sum(np.isnan(g[:, prep["keep"]])))
if n_fill:
    warnings.append(f"{n_fill} no-calls were filled with twice the variant's minor-allele frequency.")
w_kept = prep["weights"][prep["keep"]]
maf_kept = prep["maf"][prep["keep"]]

# %% Tests
r = skat.set_test(y, x, prep["g"], w_kept, binary, rho_grid)
n = len(y)
label = {"skat": "SKAT", "burden": "weighted burden test", "skato": "SKAT-O"}[test]
p = {"skat": r["p_skat"], "burden": r["p_burden"], "skato": r["p_skato"]}[test]
q = {"skat": r["q_skat"], "burden": r["q_burden"], "skato": None}[test]
cases = int(np.sum(y)) if binary else None
if r["p_skat_method"] == "liu":
    warnings.append("The exact mixture tail couldn't be resolved for SKAT, so its p-value uses Liu's moment matching.")

# %% Assumptions
assumptions = [
    {"key": "null_model", "label": "Correct null model", "status": "info",
     "detail": f"{'Logistic' if binary else 'Linear'} null model with {len(covariates)} covariate{'s' if len(covariates) != 1 else ''}"
               + (": add ancestry principal components if people come from different populations." if not covariates else ".")},
    {"key": "unrelated", "label": "Unrelated people", "status": "info", "detail": "Not checkable here: relatives would need a kinship model."},
    {"key": "weights_fixed", "label": "Weights and set fixed in advance", "status": "info",
     "detail": (f"Beta(MAF; {beta_a:g}, {beta_b:g}) weights" if weights == "beta" else "Equal weights") + f" on {len(kept)} variants."},
]
if binary:
    small = cases < 100 or n - cases < 100
    assumptions.append({"key": "sample_size", "label": "Enough cases (binary traits)", "status": "warn" if small else "pass",
                        "detail": f"{cases} cases and {n - cases} controls" + (": asymptotic p-values may be anti-conservative here." if small else ".")})
else:
    assumptions.append({"key": "sample_size", "label": "Enough cases (binary traits)", "status": "info", "detail": "A continuous trait: not applicable."})

# %% Result
summary = (f"{label} of {len(kept)} variants (cumulative minor-allele count {int(np.sum(prep['mac'][prep['keep']]))}) with {outcome} "
           f"in {n} people{f' ({cases} cases)' if binary else ''}: {cs.fmt_p(p)}.")
apa = f"{label}, {len(kept)} variants, N = {n}, {cs.fmt_p(p)}"
variant_rows = [{"variant": v, "counted": counted[variants.index(v)], "maf": float(maf_kept[i]), "mac": float(prep["mac"][variants.index(v)]),
                 "flipped": "yes" if prep["flipped"][variants.index(v)] else "", "weight": float(w_kept[i])} for i, v in enumerate(kept)]
grid_rows = [{"rho": rho_grid[i], "q": r["q_rho"][i], "p": r["p_rho"][i]} for i in range(len(rho_grid))]
tests = [{"test": "SKAT (ρ = 0)", "q": r["q_skat"], "p": r["p_skat"]},
         {"test": "Weighted burden (ρ = 1)", "q": r["q_burden"], "p": r["p_burden"]},
         {"test": "SKAT-O (min over ρ, adjusted)", "q": None, "p": r["p_skato"]}]
notes = [research_note,
         "Q follows a mixture of 1-df chi-squares (eigenvalues of the weighted score covariance); a χ² with one df per variant would be wrong.",
         f"SKAT-O's smallest grid p was {r['p_min']:.4g} at ρ = {r['rho_best']:g}; the SKAT-O p-value accounts for searching the grid, so it is larger."]
values = {
    "n": n, "n_variants_input": len(variants), "n_variants": len(kept), "n_dropped_missing": prep["n_dropped_missing"],
    "n_monomorphic": prep["n_monomorphic"], "n_flipped": int(np.sum(prep["flipped"] & prep["keep"])),
    "cmac": float(np.sum(prep["mac"][prep["keep"]])), "outcome_type": outcome_type, "test": test, "test_label": label,
    "p": p, "q": q, "p_skat": r["p_skat"], "q_skat": r["q_skat"], "p_skat_liu": r["p_skat_liu"], "p_skat_method": r["p_skat_method"],
    "p_burden": r["p_burden"], "q_burden": r["q_burden"], "p_skato": r["p_skato"], "p_min": r["p_min"], "rho_best": r["rho_best"],
    "rho": list(rho_grid), "p_rho": r["p_rho"], "q_rho": r["q_rho"], "maf": maf_kept.tolist(), "weight": w_kept.tolist(),
    "s2": r["s2"], "n_covariates": len(covariates),
}
cs.publish({
    "method": "genetics.setassoc",
    "methodVersion": "1.0.1",
    "title": label,
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": apa,
    "statistics": [
        {"key": "n_variants", "label": "Variants tested", "value": len(kept)},
        {"key": "cmac", "label": "Cumulative minor-allele count", "value": values["cmac"]},
        {"key": "q", "label": "Q", "value": q},
        {"key": "p", "label": f"p ({label})", "value": p, "format": "p"},
    ],
    "tables": [
        {"key": "tests", "title": "SKAT, burden and SKAT-O",
         "columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "q", "label": "Q", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
         "rows": tests},
        {"key": "rho_grid", "title": "SKAT-O grid",
         "columns": [{"key": "rho", "label": "ρ", "type": "number"}, {"key": "q", "label": "Q_ρ", "type": "number"}, {"key": "p", "label": "p_ρ (unadjusted)", "type": "p"}],
         "rows": grid_rows},
        {"key": "variants", "title": "Variants in the set",
         "columns": [{"key": "variant", "label": "Variant", "type": "string"}, {"key": "counted", "label": "Allele counted", "type": "string"},
                     {"key": "maf", "label": "MAF", "type": "number"}, {"key": "mac", "label": "Minor-allele count", "type": "number"},
                     {"key": "flipped", "label": "Recoded to minor", "type": "string"}, {"key": "weight", "label": "Weight", "type": "number"}],
         "rows": variant_rows},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "charts": [],
    "values": values,
})
R

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

# Rare-variant set tests (SKAT, SKAT-O, burden)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.setassoc 1.0.1 · spec 957a7d911cb9faab
# Dataset: ge_skat_guide (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_gen_* (genotypes, design), cs_skat_* (SKAT, burden, SKAT-O; Wu et al. 2011, Lee et al. 2012)

# %% Data (no rows dropped here: genotype no-calls and missing values are handled by the analysis)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ge_skat_guide.parquet", col_select = c("y", "age", "v01", "v02", "v03", "v04", "v05", "v06", "v07", "v08", "v09", "v10", "v11", "v12")))
n_input <- nrow(df)
warnings <- list()
research_note <- "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."

# %% People: trait and covariates (people missing either are left out; genotype no-calls stay)
outcome <- "y"
covariates <- c("age")
variants <- c("v01", "v02", "v03", "v04", "v05", "v06", "v07", "v08", "v09", "v10", "v11", "v12")
kinds <- list(
  "y" = "numeric",
  "age" = "numeric",
  "v01" = "numeric",
  "v02" = "numeric",
  "v03" = "numeric",
  "v04" = "numeric",
  "v05" = "numeric",
  "v06" = "numeric",
  "v07" = "numeric",
  "v08" = "numeric",
  "v09" = "numeric",
  "v10" = "numeric",
  "v11" = "numeric",
  "v12" = "numeric"
)
keep <- stats::complete.cases(df[c(outcome, covariates)])
n_left <- sum(!keep)
if (n_left > 0) warnings <- c(warnings, sprintf("%d of %d people were left out because the trait or a covariate was missing.", n_left, n_input))
df <- df[keep, , drop = FALSE]
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c(outcome, covariates))  # infinite values stop the run (registry/errors.yaml)
y <- as.numeric(df[[outcome]])
des <- cs_gen_design(df[covariates], kinds, length(y))
x <- des$x
x_names <- des$names
# Each test fits the covariates and one marker and needs at least one residual degree of freedom.
if (length(y) < ncol(x) + 2) cs_error("CS_E_TOO_FEW_ROWS", what = "The association test", min = ncol(x) + 2, n = length(y))
if (all(y == y[1])) cs_error("CS_E_CONSTANT", column = outcome)
outcome_type <- "auto"
is01 <- all(y == 0 | y == 1) && length(unique(y)) == 2
if (outcome_type == "auto") outcome_type <- if (is01) "binary" else "continuous"
if (outcome_type == "binary" && !is01) stop(sprintf("A binary trait must hold only 0 and 1, with both present; %s doesn't.", outcome), call. = FALSE)
binary <- outcome_type == "binary"
dm <- cs_gen_dose_matrix(df[variants])
g <- dm$g
counted <- dm$counted
other <- dm$other
test <- "skat"
weights <- "beta"
beta_a <- 1
beta_b <- 25
rho_grid <- cs_skat_rho_grid("adj")
max_missing <- 0.15

# %% Variants: minor-allele coding, no-calls filled with the mean, weights
prep <- cs_skat_prepare(g, max_missing, beta_a, beta_b, weights)
kept <- variants[prep$keep]
if (!length(kept)) cs_error("CS_E_UNDEFINED", what = "The set test", reason = "every variant is monomorphic here or has too many no-calls")
if (prep$n_dropped_missing > 0) {
  warnings <- c(warnings, sprintf("%d variants had more than %.0f%% no-calls and were left out.", as.integer(prep$n_dropped_missing), 100 * max_missing))
}
if (prep$n_monomorphic > 0) warnings <- c(warnings, sprintf("%d variants are monomorphic in these people and were left out.", as.integer(prep$n_monomorphic)))
n_fill <- sum(is.na(g[, prep$keep, drop = FALSE]))
if (n_fill > 0) warnings <- c(warnings, sprintf("%d no-calls were filled with twice the variant's minor-allele frequency.", as.integer(n_fill)))
w_kept <- prep$weights[prep$keep]
maf_kept <- prep$maf[prep$keep]

# %% Tests
r <- cs_skat_set_test(y, x, prep$g, w_kept, binary, rho_grid)
n <- length(y)
label <- switch(test, skat = "SKAT", burden = "weighted burden test", skato = "SKAT-O")
p <- switch(test, skat = r$p_skat, burden = r$p_burden, skato = r$p_skato)
q <- switch(test, skat = r$q_skat, burden = r$q_burden, skato = NA)
cases <- if (binary) as.integer(sum(y)) else NA
if (r$p_skat_method == "liu") warnings <- c(warnings, "The exact mixture tail couldn't be resolved for SKAT, so its p-value uses Liu's moment matching.")

# %% Assumptions
assumptions <- list(
  list(key = "null_model", label = "Correct null model", status = "info",
       detail = paste0(sprintf("%s null model with %d covariate%s", if (binary) "Logistic" else "Linear", length(covariates), if (length(covariates) != 1) "s" else ""),
                       if (!length(covariates)) ": add ancestry principal components if people come from different populations." else ".")),
  list(key = "unrelated", label = "Unrelated people", status = "info", detail = "Not checkable here: relatives would need a kinship model."),
  list(key = "weights_fixed", label = "Weights and set fixed in advance", status = "info",
       detail = paste0(if (weights == "beta") sprintf("Beta(MAF; %s, %s) weights", format(beta_a), format(beta_b)) else "Equal weights", sprintf(" on %d variants.", length(kept))))
)
if (binary) {
  small <- cases < 100 || n - cases < 100
  assumptions[[4]] <- list(key = "sample_size", label = "Enough cases (binary traits)", status = if (small) "warn" else "pass",
                           detail = paste0(sprintf("%d cases and %d controls", cases, n - cases), if (small) ": asymptotic p-values may be anti-conservative here." else "."))
} else {
  assumptions[[4]] <- list(key = "sample_size", label = "Enough cases (binary traits)", status = "info", detail = "A continuous trait: not applicable.")
}

# %% Result
cmac <- sum(prep$mac[prep$keep])
summary <- sprintf("%s of %d variants (cumulative minor-allele count %d) with %s in %d people%s: %s.",
                   label, length(kept), as.integer(cmac), outcome, n, if (binary) sprintf(" (%d cases)", cases) else "", cs_fmt_p(p))
apa <- sprintf("%s, %d variants, N = %d, %s", label, length(kept), n, cs_fmt_p(p))
idx <- match(kept, variants)
variant_rows <- lapply(seq_along(kept), function(i) list(variant = kept[i], counted = counted[idx[i]], maf = maf_kept[i], mac = prep$mac[idx[i]],
                                                       flipped = if (prep$flipped[idx[i]]) "yes" else "", weight = w_kept[i]))
grid_rows <- lapply(seq_along(rho_grid), function(i) list(rho = rho_grid[i], q = r$q_rho[i], p = r$p_rho[i]))
tests <- list(list(test = "SKAT (ρ = 0)", q = r$q_skat, p = r$p_skat),
              list(test = "Weighted burden (ρ = 1)", q = r$q_burden, p = r$p_burden),
              list(test = "SKAT-O (min over ρ, adjusted)", q = NA, p = r$p_skato))
notes <- list(research_note,
              "Q follows a mixture of 1-df chi-squares (eigenvalues of the weighted score covariance); a χ² with one df per variant would be wrong.",
              sprintf("SKAT-O's smallest grid p was %s at ρ = %s; the SKAT-O p-value accounts for searching the grid, so it is larger.",
                      formatC(r$p_min, digits = 4, format = "g"), format(r$rho_best)))
result_values <- list(
  n = n, n_variants_input = length(variants), n_variants = length(kept), n_dropped_missing = prep$n_dropped_missing,
  n_monomorphic = prep$n_monomorphic, n_flipped = sum(prep$flipped & prep$keep), cmac = cmac, outcome_type = outcome_type,
  test = test, test_label = label, p = p, q = q, p_skat = r$p_skat, q_skat = r$q_skat, p_skat_liu = r$p_skat_liu,
  p_skat_method = r$p_skat_method, p_burden = r$p_burden, q_burden = r$q_burden, p_skato = r$p_skato, p_min = r$p_min,
  rho_best = r$rho_best, rho = I(rho_grid), p_rho = I(r$p_rho), q_rho = I(r$q_rho), maf = I(unname(maf_kept)), weight = I(unname(w_kept)),
  s2 = r$s2, n_covariates = length(covariates)
)
cs_publish(list(
  method = "genetics.setassoc",
  methodVersion = "1.0.1",
  title = label,
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = apa,
  statistics = list(
    list(key = "n_variants", label = "Variants tested", value = length(kept)),
    list(key = "cmac", label = "Cumulative minor-allele count", value = cmac),
    list(key = "q", label = "Q", value = q),
    list(key = "p", label = sprintf("p (%s)", label), value = p, format = "p")
  ),
  tables = list(
    list(key = "tests", title = "SKAT, burden and SKAT-O",
         columns = list(list(key = "test", label = "Test", type = "string"), list(key = "q", label = "Q", type = "number"), list(key = "p", label = "p", type = "p")),
         rows = tests),
    list(key = "rho_grid", title = "SKAT-O grid",
         columns = list(list(key = "rho", label = "ρ", type = "number"), list(key = "q", label = "Q_ρ", type = "number"), list(key = "p", label = "p_ρ (unadjusted)", type = "p")),
         rows = grid_rows),
    list(key = "variants", title = "Variants in the set",
         columns = list(list(key = "variant", label = "Variant", type = "string"), list(key = "counted", label = "Allele counted", type = "string"),
                        list(key = "maf", label = "MAF", type = "number"), list(key = "mac", label = "Minor-allele count", type = "number"),
                        list(key = "flipped", label = "Recoded to minor", type = "string"), list(key = "weight", label = "Weight", type = "number")),
         rows = variant_rows)
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = list(),
  values = result_values
))

Sources

  • Wu, M. C., Lee, S., Cai, T., Li, Y., Boehnke, M., & Lin, X. (2011). Rare-variant association testing for sequencing data with the sequence kernel association test. American Journal of Human Genetics, 89, 82–93.
  • Lee, S., Wu, M. C., & Lin, X. (2012). Optimal tests for rare variant effects in sequencing association studies. Biostatistics, 13, 762–775.
  • Lee, S., Emond, M. J., Bamshad, M. J., et al. (2012). Optimal unified approach for rare-variant association testing with application to small-sample case-control whole-exome sequencing studies. American Journal of Human Genetics, 91, 224–237.
  • Imhof, J. P. (1961). Computing the distribution of quadratic forms in normal variables. Biometrika, 48, 419–426.
  • Liu, H., Tang, Y., & Zhang, H. H. (2009). A new chi-square approximation to the distribution of non-negative definite quadratic forms in non-central normal variables. Computational Statistics & Data Analysis, 53, 853–856.

From the CodeSplash method registry · genetics.setassoc v1.0.1.