[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ED6ACMD4NAH707QJEWY7RB":3,"skill-same:01M7ED6ACMD4NAH707QJEWY7RB":62},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":30,"commitSha":31,"skillDirectory":32,"forksCount":14,"repositoryHtmlUrl":33,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":35,"install":36,"resources":49},"01M7ED6ACMD4NAH707QJEWY7RB","bio-expression-matrix-metadata-joins",null,"Aligns sample metadata with count matrices and constructs design matrices for downstream DE, handling the alphabetical-reference-level trap (relevel BEFORE DESeq), LRT reduced-model rules, the interaction-term resultsNames trap, continuous-covariate scaling and splines, repeated measures via duplicateCorrelation or dream, high-cardinality categorical pseudo-singular designs, sample swap detection via XIST\u002FRPS4Y1 expression and somalier\u002FNGSCheckMate genotypes, SABV (sex-as-biological-variable) mandate, Simpson's-paradox collapsing of technical replicates, and the `~ 0 + group` parameterization for clean contrasts. Use when building a design matrix, troubleshooting reversed fold-change direction, encoding paired or repeated-measures designs, detecting sample swaps, deciding sex-as-covariate, or aggregating technical replicates.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-expression-matrix-metadata-joins\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-expression-matrix-metadata-joins\ndescription: Aligns sample metadata with count matrices and constructs design matrices for downstream DE, handling the alphabetical-reference-level trap (relevel BEFORE DESeq), LRT reduced-model rules, the interaction-term resultsNames trap, continuous-covariate scaling and splines, repeated measures via duplicateCorrelation or dream, high-cardinality categorical pseudo-singular designs, sample swap detection via XIST\u002FRPS4Y1 expression and somalier\u002FNGSCheckMate genotypes, SABV (sex-as-biological-variable) mandate, Simpson's-paradox collapsing of technical replicates, and the `~ 0 + group` parameterization for clean contrasts. Use when building a design matrix, troubleshooting reversed fold-change direction, encoding paired or repeated-measures designs, detecting sample swaps, deciding sex-as-covariate, or aggregating technical replicates.\ntool_type: mixed\nprimary_tool: pandas\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"expression-matrix\u002Fmetadata-joins\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: pandas 2.2+, DESeq2 1.42+, edgeR 4.0+, limma 3.58+, variancePartition \u002F dream 1.32+, somalier 0.2.18+ (CLI), pyensembl 2.3+, anndata 0.10+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- CLI: `\u003Ctool> --version` then `\u003Ctool> --help` to confirm flags\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Metadata Joins\n\n**\"Align my sample metadata with my count matrix and build a design\"** -> Reconcile sample identifiers, validate the join, set factor levels explicitly to control fold-change direction, encode the experimental structure (paired, repeated measures, interaction) in the design formula, and detect swaps before downstream DE.\n\n## The Single Most Important Modern Insight -- Alphabetical reference levels invert fold changes silently\n\nDESeq2 picks the reference level alphabetically if not told otherwise. With `condition = c('Treated', 'Untreated')`, `T \u003C U`, so `Treated` becomes the reference. The reported `log2FoldChange` is then `Untreated vs Treated` -- **the opposite of what the methods section says**. No error; the volcano plot looks plausible; the gene list is correct but with reversed sign.\n\n```r\ndds$condition \u003C- relevel(dds$condition, ref = 'Untreated')\ncoldata$condition \u003C- factor(coldata$condition, levels = c('Untreated', 'Treated'))\n```\n\nSet BEFORE `DESeq()`; relevel-then-DESeq again to take effect.\n\nA second insight: in interaction designs `~ genotype * treatment`, `results(dds, name='treatment_drug_vs_vehicle')` returns the drug effect IN THE WT REFERENCE only, not the marginal\u002Faverage effect. The interaction coefficient `genotypeKO.treatmentdrug` is the DIFFERENCE in drug effect between KO and WT (the difference of differences), NOT the drug effect in KO. The cleanest fix is to use `~ 0 + group` with `group = paste(genotype, treatment, sep='_')` so every comparison of interest is a single contrast.\n\n## Algorithmic Taxonomy\n\n| Pattern | Encoding | Tests | Caveat |\n|---------|----------|-------|--------|\n| Simple two-group | `~ condition` | `results(name='condition_treated_vs_control')` | Set reference level explicitly |\n| With known batch | `~ batch + condition` | `results(name='condition_...')` | Variable of interest LAST is the convention; not required |\n| Paired (pre\u002Fpost per subject) | `~ subject + condition` | `results(name='condition_...')` | Pairing FIRST; subject absorbs baseline variability |\n| Repeated measures (>2 time per subject) | DREAM `~ condition + (1|subject)` | `topTable(coef='condition')` | Mixed model; uses voom + lmer |\n| Interaction (2x2) | `~ A * B` (expands to A + B + A:B) | `results(name='A.B')` for diff-in-diff; combined factor for cleaner contrasts | resultsNames trap |\n| Multi-group all pairwise | `~ 0 + group` + `makeContrasts` | Contrasts named directly | DESeq2 needs intercept; works for edgeR\u002Flimma |\n| Multi-level \"any change\" | LRT `reduced = ~ 1` | `results(dds)` from LRT fit | padj is omnibus; LFC is one specific level |\n\n## Decision Tree by Scenario\n\n| Scenario | Recommended approach |\n|----------|---------------------|\n| Tumor \u002F normal paired by patient | `~ patient + tissue`; pairing FIRST -- absorbs subject variability |\n| Pre \u002F post drug, same patient (2 time points) | `~ subject + condition` |\n| Longitudinal, 4+ time points per subject | DREAM mixed model with `(1 \\| subject)` random effect |\n| Known batch (sequencing run, library prep date) | `~ batch + condition`; do NOT subtract |\n| Many batches (>10 levels, n=20-40) | `~ condition + (1 \\| batch)` via DREAM; or aggregate batches |\n| Continuous covariate (age, RIN) | Center first; include linearly OR via `ns(x, df=3)` if non-linear |\n| Mixed-sex cohort | Include sex unless sex-specific; report sex-stratified sensitivity |\n| Multi-group, want pairwise contrasts | `~ 0 + group` + `makeContrasts` |\n| Interaction question (does effect of A differ across B?) | Either `~ A * B` (handle resultsNames trap) or combined factor `~ 0 + group` |\n| Many technical reps within bio reps | `duplicateCorrelation` (limma) OR aggregate via `collapseReplicates` (DESeq2) |\n| Cohort >=20 samples | Run somalier or NGSCheckMate genotype check at the matrix-build step |\n\n## Basic Join\n\n**Goal:** Align count matrix columns with metadata rows; remove samples present in only one source; verify alignment before downstream use.\n\n**Approach:** Intersect sample identifiers; reorder both data sources; assert match.\n\n```python\nimport pandas as pd\n\ncounts = pd.read_csv('counts.tsv', sep='\\t', index_col=0)\nmetadata = pd.read_csv('metadata.csv', index_col=0)\n\ncommon = counts.columns.intersection(metadata.index)\nonly_counts = set(counts.columns) - set(metadata.index)\nonly_meta = set(metadata.index) - set(counts.columns)\nif only_counts: print(f'In counts not metadata: {only_counts}')\nif only_meta: print(f'In metadata not counts: {only_meta}')\n\ncounts = counts[common]\nmetadata = metadata.loc[common]\nassert all(counts.columns == metadata.index)\n```\n\n```r\ncommon \u003C- intersect(colnames(counts), rownames(coldata))\ncounts \u003C- counts[, common]\ncoldata \u003C- coldata[common, , drop = FALSE]\nstopifnot(all(colnames(counts) == rownames(coldata)))\n```\n\nWhen sample names differ by formatting (underscore vs dash, BAM suffix, case), try systematic transformations -- replace `_` \u003C-> `-`, strip `.bam`, lower-case, take prefix before `_` -- before giving up.\n\n## Reference Level (Critical -- Set Before DESeq)\n\n**Goal:** Pick the baseline against which fold changes are reported, controlling sign direction.\n\n**Approach:** `relevel()` or construct the factor with explicit `levels=`. Set BEFORE `DESeq()` runs.\n\n```r\ncoldata$condition \u003C- factor(coldata$condition, levels = c('control', 'treated'))\n\ncoldata$condition \u003C- relevel(coldata$condition, ref = 'control')\n```\n\n```python\nmetadata['condition'] = pd.Categorical(metadata['condition'],\n                                        categories=['control', 'treated'],\n                                        ordered=True)\n```\n\nWith factor levels explicit, the LFC reads `treated \u002F control` -- treated up means LFC > 0.\n\nA reminder for edgeR \u002F limma users: `makeContrasts(Treated - Control)` is explicit and immune to the reference-level trap. Same caution applies less because the user names the contrast.\n\n## Paired Designs\n\n```r\ndesign = ~ patient + tissue\n```\n\nPairing variable FIRST (convention). Patient absorbs inter-subject baseline variability, dramatically increasing power for the tissue effect.\n\nFor DESeq2:\n```r\ndds \u003C- DESeqDataSetFromMatrix(counts, coldata, design = ~ patient + tissue)\ndds \u003C- DESeq(dds)\nres \u003C- results(dds, name = 'tissue_tumor_vs_normal')\n```\n\nFor edgeR:\n```r\ndesign \u003C- model.matrix(~ patient + tissue, coldata)\ny \u003C- estimateDisp(y, design, robust = TRUE)\nfit \u003C- glmQLFit(y, design, robust = TRUE)\nqlf \u003C- glmQLFTest(fit, coef = 'tissuetumor')\n```\n\nCommon mistake: writing `~ tissue + patient`. Numerically the model is the same; the convention of pairing-first improves readability and matches the natural mental model.\n\n## Interaction Terms -- the resultsNames Trap\n\n```r\ndesign = ~ genotype + treatment + genotype:treatment\ndds \u003C- DESeqDataSetFromMatrix(counts, coldata, design = design)\ndds \u003C- DESeq(dds)\nresultsNames(dds)\n```\n\nOutput names (after relevel):\n```\n\"Intercept\"\n\"genotype_KO_vs_WT\"\n\"treatment_drug_vs_vehicle\"\n\"genotypeKO.treatmentdrug\"\n```\n\n| Question | Wrong answer | Right answer |\n|----------|--------------|--------------|\n| Drug effect averaged over genotypes | `results(name='treatment_drug_vs_vehicle')` -- this is drug effect in WT only | Combined factor `~ 0 + group`; or contrast that explicitly averages |\n| Is drug effect different between genotypes? | n\u002Fa | `results(name='genotypeKO.treatmentdrug')` -- the interaction coefficient IS the difference of differences |\n| Drug effect in KO | `results(name='treatment_drug_vs_vehicle')` -- WRONG, this is drug in WT | `results(contrast=list(c('treatment_drug_vs_vehicle', 'genotypeKO.treatmentdrug')))` (sum of main + interaction) |\n\nThe cleaner alternative for designs with many contrasts of interest:\n\n```r\ncoldata$group \u003C- factor(paste(coldata$genotype, coldata$treatment, sep = '_'))\ndds \u003C- DESeqDataSetFromMatrix(counts, coldata, design = ~ 0 + group)\ndds \u003C- DESeq(dds)\n\nres_drug_in_ko \u003C- results(dds, contrast = c('group', 'KO_drug', 'KO_vehicle'))\nres_drug_in_wt \u003C- results(dds, contrast = c('group', 'WT_drug', 'WT_vehicle'))\nres_diff       \u003C- results(dds, contrast = list(c('groupKO_drug', 'groupWT_vehicle'),\n                                                c('groupKO_vehicle', 'groupWT_drug')))\n```\n\n`~ 0 + group` parameterization is the long-standing edgeR \u002F limma recommendation (Smyth and Robinson User's Guides) for any design with multiple pairwise contrasts of interest.\n\n## LRT and the Reduced Model\n\n```r\ndds \u003C- DESeq(dds, test = 'LRT', reduced = ~ batch)\n```\n\nReduced model drops the term being tested. With `design = ~ batch + condition` and `reduced = ~ batch`, the LRT tests condition. With interaction designs:\n\n```r\ndds \u003C- DESeq(dds, test = 'LRT', reduced = ~ genotype + treatment)\n```\n\n(Tests the interaction.)\n\nThe reduced model must be NESTED in the full model (every term in reduced must appear in full).\n\n## Continuous Covariates\n\n| Encoding | Assumption | When |\n|----------|------------|------|\n| Linear (`+ age`) | log-expression linear in age | Limited range, biologically linear |\n| Centered linear (`+ I(age - mean(age))`) | As linear, interpretable intercept | Standard for age-RIN-day covariates |\n| Natural spline (`+ ns(age, df=3)`) | Smooth nonlinear | Wide age range with non-monotonic effects |\n| Polynomial (`+ poly(age, 2)`) | Quadratic; orthogonal polynomials | Limited use; splines usually better |\n\n```r\ncoldata$age_c \u003C- coldata$age - mean(coldata$age)\ndesign = ~ age_c + RIN + condition\n\nlibrary(splines)\ndesign = ~ ns(age, df = 3) + condition\n```\n\nDO NOT include library size as a covariate -- it is handled by size factors \u002F normalization factors internally.\n\n## Repeated Measures -- duplicateCorrelation vs dream\n\n**Goal:** Correctly model within-subject correlation when the same subject contributes multiple samples.\n\n**Approach:** For technical reps within bio reps OR paired pre\u002Fpost: `duplicateCorrelation` (limma) is adequate. For >2 time points per subject or random slopes: DREAM (`variancePartition`).\n\n```r\nlibrary(limma)\nlibrary(edgeR)\n\nv \u003C- voom(y, design)\ncorfit \u003C- duplicateCorrelation(v, design, block = coldata$donor)\nv \u003C- voom(y, design, block = coldata$donor, correlation = corfit$consensus)\ncorfit \u003C- duplicateCorrelation(v, design, block = coldata$donor)\nfit \u003C- lmFit(v, design, block = coldata$donor, correlation = corfit$consensus)\nfit \u003C- eBayes(fit, robust = TRUE)\n```\n\nThe double pass is intentional: estimate correlation, re-voom with correlation, re-estimate, fit. Limma's `duplicateCorrelation` assumes ONE within-subject correlation across all genes -- approximation.\n\nFor proper per-gene mixed models:\n\n```r\nlibrary(variancePartition)\n\nform \u003C- ~ condition + (1 | donor)\nvobj \u003C- voomWithDreamWeights(y, form, coldata)\nfitmm \u003C- dream(vobj, form, coldata)\nfitmm \u003C- eBayes(fitmm)\ntt \u003C- topTable(fitmm, coef = 'condition')\n```\n\nSee `differential-expression\u002Ftimeseries-de` for full longitudinal designs.\n\nBefore committing to a design, `variancePartition::fitExtractVarPartModel(vobj, form, coldata)` quantifies the fraction of expression variance explained by each covariate, gene-by-gene. If a candidate \"nuisance\" covariate explains \u003C1% of variance across most genes, it can usually be dropped; if a known biological factor explains \u003C5% and isn't of direct interest, model it as a random effect rather than fixed.\n\n## Sample Swap Detection (Mandatory for Cohort >= 20)\n\n### Sex check via XIST and chrY expression\n\n**Goal:** Detect mislabeled samples by checking that gene-expression sex matches reported sex.\n\n**Approach:** Compare XIST expression (high in XX, low\u002Fabsent in XY) against chrY-gene expression (DDX3Y, RPS4Y1, UTY, KDM5D, EIF1AY -- high in XY, absent in XX).\n\n```python\nimport pandas as pd\n\ndef sex_check(counts, metadata, sex_column='sex'):\n    y_genes = ['DDX3Y', 'RPS4Y1', 'UTY', 'KDM5D', 'EIF1AY']\n    y_avail = [g for g in y_genes if g in counts.index]\n    if 'XIST' not in counts.index or not y_avail:\n        return None\n    predicted = pd.Series('unknown', index=counts.columns)\n    predicted[counts.loc[y_avail].sum() > counts.loc['XIST']] = 'M'\n    predicted[counts.loc['XIST'] > counts.loc[y_avail].sum()] = 'F'\n    if sex_column in metadata.columns:\n        mis = predicted != metadata[sex_column]\n        if mis.any():\n            print(f'SEX MISMATCHES: {list(metadata.index[mis])}')\n    return predicted\n```\n\n```r\nsex_check \u003C- function(counts, coldata, sex_col = 'sex') {\n    y_genes \u003C- c('DDX3Y', 'RPS4Y1', 'UTY', 'KDM5D', 'EIF1AY')\n    y_expr \u003C- colSums(counts[intersect(y_genes, rownames(counts)), , drop = FALSE])\n    predicted \u003C- ifelse(y_expr > counts['XIST', ], 'M', 'F')\n    mis \u003C- predicted != coldata[[sex_col]]\n    if (any(mis)) cat('Sex mismatches:', colnames(counts)[mis], '\\n')\n    predicted\n}\n```\n\nCAVEAT: tumors with X loss, sex chromosome aneuploidies, HeLa (XXX with mixed inactivation) muddy this. Genotype-based methods are more robust.\n\n### Genotype-based: somalier and NGSCheckMate\n\n```bash\nsomalier extract -d extracted\u002F --sites sites.GRCh38.vcf.gz \\\n    -f reference.fa sample.bam\nsomalier relate --infer extracted\u002F*.somalier\n```\n\n```bash\nncm_fastq.py -l fastq_list.txt -O outdir -bed common_sites.bed\n```\n\nSomalier (Pedersen et al. 2020 *Genome Med* 12:62) extracts a few thousand SNP sketches per sample (sub-second per sample) and computes pairwise relatedness from BAM\u002FCRAM\u002FVCF. NGSCheckMate (Lee et al. 2017 *NAR* 45:e103) computes VAF correlation across a common-SNP panel; works on FASTQ\u002FBAM\u002FVCF including RNA-seq.\n\nFor any cohort >=20 samples, run one of these at the matrix-build step. Catching a swap in raw data is cheap; finding it after DE is expensive.\n\n## SABV -- Sex as Biological Variable\n\nNIH 2016+ requires sex consideration in vertebrate animal and human studies. Mauvais-Jarvis F et al. 2020 *Lancet* 396:565 reviews effect-size differences across diseases.\n\nPractical implication:\n- Always include sex in the metadata, even when not in the model.\n- For sex-balanced cohorts, `~ sex + condition` rarely hurts and captures real biology.\n- For sex-confounded cohorts (all-male disease cohort vs mixed-sex control), can't rescue but documents the limitation.\n- For chrX\u002FchrY analyses, sex MUST be in the model OR the analysis is uninterpretable.\n- Report DE counts overall AND sex-stratified.\n\n## Simpson's Paradox -- Collapsing Technical Replicates\n\n**Goal:** Aggregate technical replicates from the same subject correctly; never treat them as independent biological replicates.\n\n**Approach:** Sum (not average) technical replicates of the same subject BEFORE downstream DE.\n\n```r\nlibrary(DESeq2)\ndds_collapsed \u003C- collapseReplicates(dds, groupby = dds$subject)\n```\n\n```python\ncounts_per_subject = counts.T.groupby(metadata['subject']).sum().T\nmetadata_per_subject = metadata.drop_duplicates(subset='subject').set_index('subject')\n```\n\nWhy sum and not average? Reads add. Two technical replicates yielding 1M reads each are equivalent to one library yielding 2M reads. Averaging would understate the effective library size.\n\nTreating technical replicates as independent biological samples is the cardinal sin: it inflates the apparent sample size and deflates standard errors. With 4 patients x 3 tech reps = 12 samples, naive DE assumes 12 independent observations; the truth is closer to 4. p-values are compressed ~3x.\n\n## High-Cardinality Categorical Covariates\n\n**Goal:** Handle batch \u002F lane \u002F well covariates with many levels without making the design matrix singular.\n\n**Approach:** Aggregate to fewer levels, model as random effect via DREAM, or drop if confounded.\n\n```r\nct \u003C- table(coldata$condition, coldata$batch)\nct\n\nad \u003C- alias(model.matrix(~ batch + condition, coldata))\nad$Complete\n```\n\nFor a batch with 30 levels in n=40 samples: 30 batch coefficients + condition + intercept = 32 parameters for 40 observations. Symptoms: `Matrix not positive definite` (DESeq2), degenerate p-values (limma).\n\nFixes:\n- Aggregate batches (sequencing run, sequencing pool, library prep date as proxy).\n- Random effect: `~ condition + (1 | batch)` via DREAM borrows information across batch levels via shrinkage.\n- Drop the covariate if confounded with condition (`alias()` reveals collinearity).\n\n## ~ 0 + group Parameterization\n\n```r\ndesign_default \u003C- model.matrix(~ group, coldata)\n# columns: (Intercept), groupB, groupC  -- A is reference\n\ndesign_nointercept \u003C- model.matrix(~ 0 + group, coldata)\n# columns: groupA, groupB, groupC  -- each column is mean of that group\n```\n\nWith `~ 0 + group`, every contrast reads as `B - A`:\n\n```r\nlibrary(limma)\n\ncon \u003C- makeContrasts(BvsA = groupB - groupA,\n                     CvsA = groupC - groupA,\n                     BvsC = groupB - groupC,\n                     levels = design_nointercept)\nfit \u003C- glmQLFit(y, design_nointercept, robust = TRUE)\nqlf \u003C- glmQLFTest(fit, contrast = con[, 'BvsA'])\n```\n\nDESeq2 needs an intercept internally, so `~ 0 + group` works directly with edgeR\u002Flimma but DESeq2 uses `contrast=` to achieve the same effect.\n\n## Create DESeq2 \u002F edgeR \u002F AnnData Containers\n\n```r\ndds \u003C- DESeqDataSetFromMatrix(as.matrix(counts), coldata, design = ~ batch + condition)\n\ny \u003C- DGEList(counts = as.matrix(counts), group = coldata$condition)\ny$samples \u003C- cbind(y$samples, coldata)\n\nadata \u003C- ad.AnnData(X = t(as.matrix(counts)), obs = coldata, var = data.frame(row.names = rownames(counts)))\n```\n\nAnnData convention is cells (samples) in rows -- transpose from the typical R genes-in-rows convention.\n\n## Per-Method Failure Modes\n\n### Fold-change direction reversed\n\n**Trigger:** Methods says \"treated vs control\"; published volcano shows expected up-genes on the LEFT.\n\n**Mechanism:** Factor levels left at alphabetical default; `c('Treated','Untreated')` -> `T \u003C U` -> Treated is reference -> LFC is Untreated\u002FTreated.\n\n**Symptom:** Known up-regulated genes appear down; reviewer questions direction.\n\n**Fix:** `relevel(coldata$condition, ref = 'Untreated')` BEFORE `DESeq()`. Re-run.\n\n### Interaction coefficient mistaken for main effect\n\n**Trigger:** `~ A * B` design; `results(name='B_drug_vs_vehicle')` reported as \"drug effect\"; reviewer asks about genotype-specific effect.\n\n**Mechanism:** With interaction, `B_drug_vs_vehicle` is drug effect IN THE A REFERENCE LEVEL only, not averaged across A.\n\n**Symptom:** Drug effect doesn't match the marginal estimate from a separate `~ B`-only fit.\n\n**Fix:** Use `~ 0 + group` with combined factor; OR extract per-stratum results explicitly using contrasts that sum main + interaction.\n\n### Pseudoreplication -- 12 samples, only 3 subjects\n\n**Trigger:** 3 subjects x 4 conditions = 12 samples; vanilla DESeq2 with `~ condition`; many DE genes.\n\n**Mechanism:** Same subject contributes multiple observations; not independent. Effective sample size for testing condition is ~3, not 12.\n\n**Symptom:** p-value histogram anti-conservative; replication low.\n\n**Fix:** Include subject in design (`~ subject + condition`) OR use DREAM with random subject.\n\n### Sample swap caught in DE results, not metadata\n\n**Trigger:** PCA shows \"control\" sample clustering with treated; investigation reveals it was mislabeled at thaw.\n\n**Mechanism:** Manual sample tracking is error-prone; cohort >=20 inevitably has swaps.\n\n**Symptom:** One sample dramatically off its group cluster; DE gene list dominated by sample-specific effects.\n\n**Fix:** Run somalier or NGSCheckMate at the matrix-build step, BEFORE DE. Catching a swap early is cheap; finding it post-DE is expensive.\n\n### Sex confounded, chrY genes dominate top hits\n\n**Trigger:** Mixed-sex cohort; sex not in design; PCA shows clear sex split on PC1.\n\n**Mechanism:** Sex distribution differs between groups; \"treatment effect\" partially captures sex.\n\n**Symptom:** Top DE genes are DDX3Y, RPS4Y1, UTY (chrY) and XIST -- not biology of interest.\n\n**Fix:** Add sex to design (`~ sex + condition`). For sex-specific analyses, stratify and report each separately.\n\n### duplicateCorrelation single-pass\n\n**Trigger:** limma user wrote a one-pass `duplicateCorrelation` + lmFit; QC reviewer asks why no re-voom.\n\n**Mechanism:** The proper pattern is: voom -> dupCor -> re-voom WITH correlation -> dupCor again -> lmFit. The first voom doesn't know about block structure; re-voom with correlation gets better weights.\n\n**Symptom:** Slightly inflated DE counts vs the two-pass pattern.\n\n**Fix:** Implement the two-pass pattern per the limma User's Guide (section 9.7).\n\n## Common errors\n\n| Error \u002F symptom | Cause | Fix |\n|-----------------|-------|-----|\n| Sample names don't match between counts and metadata | Underscore\u002Fdash inconsistency, BAM suffix, case | `fuzzy_match_samples()` or manual normalization; report what failed |\n| DESeq2 design not full rank | Confounded covariates | `alias(design)$Complete` to identify; aggregate or drop |\n| `Matrix not positive definite` | High-cardinality batch with few samples | Aggregate batches or use random effect via DREAM |\n| LFC direction reversed | Alphabetical reference level | `relevel()` before `DESeq()` |\n| `results(name='...')` returns drug effect in WT only | Interaction design and naming trap | Use combined factor `~ 0 + group`; or contrast summing main + interaction |\n| Inflated DE list with 12 samples from 3 subjects | Pseudoreplication | Include subject; or use DREAM |\n| Sex effect appears as treatment effect | Sex not in design | Add `~ sex + condition` |\n| Sample distance heatmap shows mixing groups | Likely swap | Run somalier or NGSCheckMate |\n\n## References\n\n- Love MI, Huber W, Anders S. 2014. Moderated estimation of fold change and dispersion for RNA-seq data with DESeq2. *Genome Biol* 15(12):550. doi:10.1186\u002Fs13059-014-0550-8\n- Robinson MD, McCarthy DJ, Smyth GK. 2010. edgeR: a Bioconductor package for differential expression analysis of digital gene expression data. *Bioinformatics* 26(1):139-140. doi:10.1093\u002Fbioinformatics\u002Fbtp616\n- Ritchie ME et al. 2015. limma powers differential expression analyses for RNA-sequencing and microarray studies. *Nucleic Acids Res* 43(7):e47. doi:10.1093\u002Fnar\u002Fgkv007\n- Smyth GK, Michaud J, Scott HS. 2005. Use of within-array replicate spots for assessing differential expression in microarray experiments. *Bioinformatics* 21(9):2067-2075. doi:10.1093\u002Fbioinformatics\u002Fbti270\n- Hoffman GE, Roussos P. 2021. dream: powerful differential expression analysis for repeated measures designs. *Bioinformatics* 37(2):192-201. doi:10.1093\u002Fbioinformatics\u002Fbtaa687\n- Hoffman GE, Schadt EE. 2016. variancePartition: interpreting drivers of variation in complex gene expression studies. *BMC Bioinformatics* 17:483. doi:10.1186\u002Fs12859-016-1323-z\n- Pedersen BS, Bhetariya PJ, Brown J, Kravitz SN, Marth GT, Jensen RL, Bronner MP, Underhill HR, Quinlan AR. 2020. Somalier: rapid relatedness estimation for cancer and germline studies using efficient genome sketches. *Genome Medicine* 12:62. doi:10.1186\u002Fs13073-020-00761-2\n- Lee S, Lee S, Ouellette S, Park W-Y, Lee EA, Park PJ. 2017. NGSCheckMate: software for validating sample identity in next-generation sequencing studies within and across data types. *Nucleic Acids Res* 45(11):e103. doi:10.1093\u002Fnar\u002Fgkx193\n- Mauvais-Jarvis F, Bairey Merz N, Barnes PJ et al. 2020. Sex and gender: modifiers of health, disease, and medicine. *Lancet* 396(10250):565-582. doi:10.1016\u002FS0140-6736(20)31561-0\n\n## Related Skills\n\n- counts-ingest - Building count matrices before metadata join\n- gene-id-mapping - Annotating result tables with symbols\n- normalization - Reference for downstream normalization choice\n- sparse-handling - AnnData obs metadata convention\n- differential-expression\u002Fdeseq2-basics - Where the design formula matters; relevel; interactions\n- differential-expression\u002Fedger-basics - edgeR design matrix conventions\n- differential-expression\u002Fbatch-correction - Design-inclusion vs subtraction; confounding\n- differential-expression\u002Ftimeseries-de - Repeated measures; DREAM mixed model details\n- single-cell\u002Fpreprocessing - scRNA-seq sample metadata handling\n","## Version Compatibility\n\nReference examples tested with: pandas 2.2+, DESeq2 1.42+, edgeR 4.0+, limma 3.58+, variancePartition \u002F dream 1.32+, somalier 0.2.18+ (CLI), pyensembl 2.3+, anndata 0.10+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- CLI: `\u003Ctool> --version` then `\u003Ctool> --help` to confirm flags\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Metadata Joins\n\n**\"Align my sample metadata with my count matrix and build a design\"** -> Reconcile sample identifiers, validate the join, set factor levels explicitly to control fold-change direction, encode the experimental structure (paired, repeated measures, interaction) in the design formula, and detect swaps before downstream DE.\n\n## The Single Most Important Modern Insight -- Alphabetical reference levels invert fold changes silently\n\nDESeq2 picks the reference level alphabetically if not told otherwise. With `condition = c('Treated', 'Untreated')`, `T \u003C U`, so `Treated` becomes the reference. The reported `log2FoldChange` is then `Untreated vs Treated` -- **the opposite of what the methods section says**. No error; the volcano plot looks plausible; the gene list is correct but with reversed sign.\n\n```r\ndds$condition \u003C- relevel(dds$condition, ref = 'Untreated')\ncoldata$condition \u003C- factor(coldata$condition, levels = c('Untreated', 'Treated'))\n```\n\nSet BEFORE `DESeq()`; relevel-then-DESeq again to take effect.\n\nA second insight: in interaction designs `~ genotype * treatment`, `results(dds, name='treatment_drug_vs_vehicle')` returns the drug effect IN THE WT REFERENCE only, not the marginal\u002Faverage effect. The interaction coefficient `genotypeKO.treatmentdrug` is the DIFFERENCE in drug effect between KO and WT (the difference of differences), NOT the drug effect in KO. The cleanest fix is to use `~ 0 + group` with `group = paste(genotype, treatment, sep='_')` so every comparison of interest is a single contrast.\n\n## Algorithmic Taxonomy\n\n| Pattern | Encoding | Tests | Caveat |\n|---------|----------|-------|--------|\n| Simple two-group | `~ condition` | `results(name='condition_treated_vs_control')` | Set reference level explicitly |\n| With known batch | `~ batch + condition` | `results(name='condition_...')` | Variable of interest LAST is the convention; not required |\n| Paired (pre\u002Fpost per subject) | `~ subject + condition` | `results(name='condition_...')` | Pairing FIRST; subject absorbs baseline variability |\n| Repeated measures (>2 time per subject) | DREAM `~ condition + (1|subject)` | `topTable(coef='condition')` | Mixed model; uses voom + lmer |\n| Interaction (2x2) | `~ A * B` (expands to A + B + A:B) | `results(name='A.B')` for diff-in-diff; combined factor for cleaner contrasts | resultsNames trap |\n| Multi-group all pairwise | `~ 0 + group` + `makeContrasts` | Contrasts named directly | DESeq2 needs intercept; works for edgeR\u002Flimma |\n| Multi-level \"any change\" | LRT `reduced = ~ 1` | `results(dds)` from LRT fit | padj is omnibus; LFC is one specific level |\n\n## Decision Tree by Scenario\n\n| Scenario | Recommended approach |\n|----------|---------------------|\n| Tumor \u002F normal paired by patient | `~ patient + tissue`; pairing FIRST -- absorbs subject variability |\n| Pre \u002F post drug, same patient (2 time points) | `~ subject + condition` |\n| Longitudinal, 4+ time points per subject | DREAM mixed model with `(1 \\| subject)` random effect |\n| Known batch (sequencing run, library prep date) | `~ batch + condition`; do NOT subtract |\n| Many batches (>10 levels, n=20-40) | `~ condition + (1 \\| batch)` via DREAM; or aggregate batches |\n| Continuous covariate (age, RIN) | Center first; include linearly OR via `ns(x, df=3)` if non-linear |\n| Mixed-sex cohort | Include sex unless sex-specific; report sex-stratified sensitivity |\n| Multi-group, want pairwise contrasts | `~ 0 + group` + `makeContrasts` |\n| Interaction question (does effect of A differ across B?) | Either `~ A * B` (handle resultsNames trap) or combined factor `~ 0 + group` |\n| Many technical reps within bio reps | `duplicateCorrelation` (limma) OR aggregate via `collapseReplicates` (DESeq2) |\n| Cohort >=20 samples | Run somalier or NGSCheckMate genotype check at the matrix-build step |\n\n## Basic Join\n\n**Goal:** Align count matrix columns with metadata rows; remove samples present in only one source; verify alignment before downstream use.\n\n**Approach:** Intersect sample identifiers; reorder both data sources; assert match.\n\n```python\nimport pandas as pd\n\ncounts = pd.read_csv('counts.tsv', sep='\\t', index_col=0)\nmetadata = pd.read_csv('metadata.csv', index_col=0)\n\ncommon = counts.columns.intersection(metadata.index)\nonly_counts = set(counts.columns) - set(metadata.index)\nonly_meta = set(metadata.index) - set(counts.columns)\nif only_counts: print(f'In counts not metadata: {only_counts}')\nif only_meta: print(f'In metadata not counts: {only_meta}')\n\ncounts = counts[common]\nmetadata = metadata.loc[common]\nassert all(counts.columns == metadata.index)\n```\n\n```r\ncommon \u003C- intersect(colnames(counts), rownames(coldata))\ncounts \u003C- counts[, common]\ncoldata \u003C- coldata[common, , drop = FALSE]\nstopifnot(all(colnames(counts) == rownames(coldata)))\n```\n\nWhen sample names differ by formatting (underscore vs dash, BAM suffix, case), try systematic transformations -- replace `_` \u003C-> `-`, strip `.bam`, lower-case, take prefix before `_` -- before giving up.\n\n## Reference Level (Critical -- Set Before DESeq)\n\n**Goal:** Pick the baseline against which fold changes are reported, controlling sign direction.\n\n**Approach:** `relevel()` or construct the factor with explicit `levels=`. Set BEFORE `DESeq()` runs.\n\n```r\ncoldata$condition \u003C- factor(coldata$condition, levels = c('control', 'treated'))\n\ncoldata$condition \u003C- relevel(coldata$condition, ref = 'control')\n```\n\n```python\nmetadata['condition'] = pd.Categorical(metadata['condition'],\n                                        categories=['control', 'treated'],\n                                        ordered=True)\n```\n\nWith factor levels explicit, the LFC reads `treated \u002F control` -- treated up means LFC > 0.\n\nA reminder for edgeR \u002F limma users: `makeContrasts(Treated - Control)` is explicit and immune to the reference-level trap. Same caution applies less because the user names the contrast.\n\n## Paired Designs\n\n```r\ndesign = ~ patient + tissue\n```\n\nPairing variable FIRST (convention). Patient absorbs inter-subject baseline variability, dramatically increasing power for the tissue effect.\n\nFor DESeq2:\n```r\ndds \u003C- DESeqDataSetFromMatrix(counts, coldata, design = ~ patient + tissue)\ndds \u003C- DESeq(dds)\nres \u003C- results(dds, name = 'tissue_tumor_vs_normal')\n```\n\nFor edgeR:\n```r\ndesign \u003C- model.matrix(~ patient + tissue, coldata)\ny \u003C- estimateDisp(y, design, robust = TRUE)\nfit \u003C- glmQLFit(y, design, robust = TRUE)\nqlf \u003C- glmQLFTest(fit, coef = 'tissuetumor')\n```\n\nCommon mistake: writing `~ tissue + patient`. Numerically the model is the same; the convention of pairing-first improves readability and matches the natural mental model.\n\n## Interaction Terms -- the resultsNames Trap\n\n```r\ndesign = ~ genotype + treatment + genotype:treatment\ndds \u003C- DESeqDataSetFromMatrix(counts, coldata, design = design)\ndds \u003C- DESeq(dds)\nresultsNames(dds)\n```\n\nOutput names (after relevel):\n```\n\"Intercept\"\n\"genotype_KO_vs_WT\"\n\"treatment_drug_vs_vehicle\"\n\"genotypeKO.treatmentdrug\"\n```\n\n| Question | Wrong answer | Right answer |\n|----------|--------------|--------------|\n| Drug effect averaged over genotypes | `results(name='treatment_drug_vs_vehicle')` -- this is drug effect in WT only | Combined factor `~ 0 + group`; or contrast that explicitly averages |\n| Is drug effect different between genotypes? | n\u002Fa | `results(name='genotypeKO.treatmentdrug')` -- the interaction coefficient IS the difference of differences |\n| Drug effect in KO | `results(name='treatment_drug_vs_vehicle')` -- WRONG, this is drug in WT | `results(contrast=list(c('treatment_drug_vs_vehicle', 'genotypeKO.treatmentdrug')))` (sum of main + interaction) |\n\nThe cleaner alternative for designs with many contrasts of interest:\n\n```r\ncoldata$group \u003C- factor(paste(coldata$genotype, coldata$treatment, sep = '_'))\ndds \u003C- DESeqDataSetFromMatrix(counts, coldata, design = ~ 0 + group)\ndds \u003C- DESeq(dds)\n\nres_drug_in_ko \u003C- results(dds, contrast = c('group', 'KO_drug', 'KO_vehicle'))\nres_drug_in_wt \u003C- results(dds, contrast = c('group', 'WT_drug', 'WT_vehicle'))\nres_diff       \u003C- results(dds, contrast = list(c('groupKO_drug', 'groupWT_vehicle'),\n                                                c('groupKO_vehicle', 'groupWT_drug')))\n```\n\n`~ 0 + group` parameterization is the long-standing edgeR \u002F limma recommendation (Smyth and Robinson User's Guides) for any design with multiple pairwise contrasts of interest.\n\n## LRT and the Reduced Model\n\n```r\ndds \u003C- DESeq(dds, test = 'LRT', reduced = ~ batch)\n```\n\nReduced model drops the term being tested. With `design = ~ batch + condition` and `reduced = ~ batch`, the LRT tests condition. With interaction designs:\n\n```r\ndds \u003C- DESeq(dds, test = 'LRT', reduced = ~ genotype + treatment)\n```\n\n(Tests the interaction.)\n\nThe reduced model must be NESTED in the full model (every term in reduced must appear in full).\n\n## Continuous Covariates\n\n| Encoding | Assumption | When |\n|----------|------------|------|\n| Linear (`+ age`) | log-expression linear in age | Limited range, biologically linear |\n| Centered linear (`+ I(age - mean(age))`) | As linear, interpretable intercept | Standard for age-RIN-day covariates |\n| Natural spline (`+ ns(age, df=3)`) | Smooth nonlinear | Wide age range with non-monotonic effects |\n| Polynomial (`+ poly(age, 2)`) | Quadratic; orthogonal polynomials | Limited use; splines usually better |\n\n```r\ncoldata$age_c \u003C- coldata$age - mean(coldata$age)\ndesign = ~ age_c + RIN + condition\n\nlibrary(splines)\ndesign = ~ ns(age, df = 3) + condition\n```\n\nDO NOT include library size as a covariate -- it is handled by size factors \u002F normalization factors internally.\n\n## Repeated Measures -- duplicateCorrelation vs dream\n\n**Goal:** Correctly model within-subject correlation when the same subject contributes multiple samples.\n\n**Approach:** For technical reps within bio reps OR paired pre\u002Fpost: `duplicateCorrelation` (limma) is adequate. For >2 time points per subject or random slopes: DREAM (`variancePartition`).\n\n```r\nlibrary(limma)\nlibrary(edgeR)\n\nv \u003C- voom(y, design)\ncorfit \u003C- duplicateCorrelation(v, design, block = coldata$donor)\nv \u003C- voom(y, design, block = coldata$donor, correlation = corfit$consensus)\ncorfit \u003C- duplicateCorrelation(v, design, block = coldata$donor)\nfit \u003C- lmFit(v, design, block = coldata$donor, correlation = corfit$consensus)\nfit \u003C- eBayes(fit, robust = TRUE)\n```\n\nThe double pass is intentional: estimate correlation, re-voom with correlation, re-estimate, fit. Limma's `duplicateCorrelation` assumes ONE within-subject correlation across all genes -- approximation.\n\nFor proper per-gene mixed models:\n\n```r\nlibrary(variancePartition)\n\nform \u003C- ~ condition + (1 | donor)\nvobj \u003C- voomWithDreamWeights(y, form, coldata)\nfitmm \u003C- dream(vobj, form, coldata)\nfitmm \u003C- eBayes(fitmm)\ntt \u003C- topTable(fitmm, coef = 'condition')\n```\n\nSee `differential-expression\u002Ftimeseries-de` for full longitudinal designs.\n\nBefore committing to a design, `variancePartition::fitExtractVarPartModel(vobj, form, coldata)` quantifies the fraction of expression variance explained by each covariate, gene-by-gene. If a candidate \"nuisance\" covariate explains \u003C1% of variance across most genes, it can usually be dropped; if a known biological factor explains \u003C5% and isn't of direct interest, model it as a random effect rather than fixed.\n\n## Sample Swap Detection (Mandatory for Cohort >= 20)\n\n### Sex check via XIST and chrY expression\n\n**Goal:** Detect mislabeled samples by checking that gene-expression sex matches reported sex.\n\n**Approach:** Compare XIST expression (high in XX, low\u002Fabsent in XY) against chrY-gene expression (DDX3Y, RPS4Y1, UTY, KDM5D, EIF1AY -- high in XY, absent in XX).\n\n```python\nimport pandas as pd\n\ndef sex_check(counts, metadata, sex_column='sex'):\n    y_genes = ['DDX3Y', 'RPS4Y1', 'UTY', 'KDM5D', 'EIF1AY']\n    y_avail = [g for g in y_genes if g in counts.index]\n    if 'XIST' not in counts.index or not y_avail:\n        return None\n    predicted = pd.Series('unknown', index=counts.columns)\n    predicted[counts.loc[y_avail].sum() > counts.loc['XIST']] = 'M'\n    predicted[counts.loc['XIST'] > counts.loc[y_avail].sum()] = 'F'\n    if sex_column in metadata.columns:\n        mis = predicted != metadata[sex_column]\n        if mis.any():\n            print(f'SEX MISMATCHES: {list(metadata.index[mis])}')\n    return predicted\n```\n\n```r\nsex_check \u003C- function(counts, coldata, sex_col = 'sex') {\n    y_genes \u003C- c('DDX3Y', 'RPS4Y1', 'UTY', 'KDM5D', 'EIF1AY')\n    y_expr \u003C- colSums(counts[intersect(y_genes, rownames(counts)), , drop = FALSE])\n    predicted \u003C- ifelse(y_expr > counts['XIST', ], 'M', 'F')\n    mis \u003C- predicted != coldata[[sex_col]]\n    if (any(mis)) cat('Sex mismatches:', colnames(counts)[mis], '\\n')\n    predicted\n}\n```\n\nCAVEAT: tumors with X loss, sex chromosome aneuploidies, HeLa (XXX with mixed inactivation) muddy this. Genotype-based methods are more robust.\n\n### Genotype-based: somalier and NGSCheckMate\n\n```bash\nsomalier extract -d extracted\u002F --sites sites.GRCh38.vcf.gz \\\n    -f reference.fa sample.bam\nsomalier relate --infer extracted\u002F*.somalier\n```\n\n```bash\nncm_fastq.py -l fastq_list.txt -O outdir -bed common_sites.bed\n```\n\nSomalier (Pedersen et al. 2020 *Genome Med* 12:62) extracts a few thousand SNP sketches per sample (sub-second per sample) and computes pairwise relatedness from BAM\u002FCRAM\u002FVCF. NGSCheckMate (Lee et al. 2017 *NAR* 45:e103) computes VAF correlation across a common-SNP panel; works on FASTQ\u002FBAM\u002FVCF including RNA-seq.\n\nFor any cohort >=20 samples, run one of these at the matrix-build step. Catching a swap in raw data is cheap; finding it after DE is expensive.\n\n## SABV -- Sex as Biological Variable\n\nNIH 2016+ requires sex consideration in vertebrate animal and human studies. Mauvais-Jarvis F et al. 2020 *Lancet* 396:565 reviews effect-size differences across diseases.\n\nPractical implication:\n- Always include sex in the metadata, even when not in the model.\n- For sex-balanced cohorts, `~ sex + condition` rarely hurts and captures real biology.\n- For sex-confounded cohorts (all-male disease cohort vs mixed-sex control), can't rescue but documents the limitation.\n- For chrX\u002FchrY analyses, sex MUST be in the model OR the analysis is uninterpretable.\n- Report DE counts overall AND sex-stratified.\n\n## Simpson's Paradox -- Collapsing Technical Replicates\n\n**Goal:** Aggregate technical replicates from the same subject correctly; never treat them as independent biological replicates.\n\n**Approach:** Sum (not average) technical replicates of the same subject BEFORE downstream DE.\n\n```r\nlibrary(DESeq2)\ndds_collapsed \u003C- collapseReplicates(dds, groupby = dds$subject)\n```\n\n```python\ncounts_per_subject = counts.T.groupby(metadata['subject']).sum().T\nmetadata_per_subject = metadata.drop_duplicates(subset='subject').set_index('subject')\n```\n\nWhy sum and not average? Reads add. Two technical replicates yielding 1M reads each are equivalent to one library yielding 2M reads. Averaging would understate the effective library size.\n\nTreating technical replicates as independent biological samples is the cardinal sin: it inflates the apparent sample size and deflates standard errors. With 4 patients x 3 tech reps = 12 samples, naive DE assumes 12 independent observations; the truth is closer to 4. p-values are compressed ~3x.\n\n## High-Cardinality Categorical Covariates\n\n**Goal:** Handle batch \u002F lane \u002F well covariates with many levels without making the design matrix singular.\n\n**Approach:** Aggregate to fewer levels, model as random effect via DREAM, or drop if confounded.\n\n```r\nct \u003C- table(coldata$condition, coldata$batch)\nct\n\nad \u003C- alias(model.matrix(~ batch + condition, coldata))\nad$Complete\n```\n\nFor a batch with 30 levels in n=40 samples: 30 batch coefficients + condition + intercept = 32 parameters for 40 observations. Symptoms: `Matrix not positive definite` (DESeq2), degenerate p-values (limma).\n\nFixes:\n- Aggregate batches (sequencing run, sequencing pool, library prep date as proxy).\n- Random effect: `~ condition + (1 | batch)` via DREAM borrows information across batch levels via shrinkage.\n- Drop the covariate if confounded with condition (`alias()` reveals collinearity).\n\n## ~ 0 + group Parameterization\n\n```r\ndesign_default \u003C- model.matrix(~ group, coldata)\n# columns: (Intercept), groupB, groupC  -- A is reference\n\ndesign_nointercept \u003C- model.matrix(~ 0 + group, coldata)\n# columns: groupA, groupB, groupC  -- each column is mean of that group\n```\n\nWith `~ 0 + group`, every contrast reads as `B - A`:\n\n```r\nlibrary(limma)\n\ncon \u003C- makeContrasts(BvsA = groupB - groupA,\n                     CvsA = groupC - groupA,\n                     BvsC = groupB - groupC,\n                     levels = design_nointercept)\nfit \u003C- glmQLFit(y, design_nointercept, robust = TRUE)\nqlf \u003C- glmQLFTest(fit, contrast = con[, 'BvsA'])\n```\n\nDESeq2 needs an intercept internally, so `~ 0 + group` works directly with edgeR\u002Flimma but DESeq2 uses `contrast=` to achieve the same effect.\n\n## Create DESeq2 \u002F edgeR \u002F AnnData Containers\n\n```r\ndds \u003C- DESeqDataSetFromMatrix(as.matrix(counts), coldata, design = ~ batch + condition)\n\ny \u003C- DGEList(counts = as.matrix(counts), group = coldata$condition)\ny$samples \u003C- cbind(y$samples, coldata)\n\nadata \u003C- ad.AnnData(X = t(as.matrix(counts)), obs = coldata, var = data.frame(row.names = rownames(counts)))\n```\n\nAnnData convention is cells (samples) in rows -- transpose from the typical R genes-in-rows convention.\n\n## Per-Method Failure Modes\n\n### Fold-change direction reversed\n\n**Trigger:** Methods says \"treated vs control\"; published volcano shows expected up-genes on the LEFT.\n\n**Mechanism:** Factor levels left at alphabetical default; `c('Treated','Untreated')` -> `T \u003C U` -> Treated is reference -> LFC is Untreated\u002FTreated.\n\n**Symptom:** Known up-regulated genes appear down; reviewer questions direction.\n\n**Fix:** `relevel(coldata$condition, ref = 'Untreated')` BEFORE `DESeq()`. Re-run.\n\n### Interaction coefficient mistaken for main effect\n\n**Trigger:** `~ A * B` design; `results(name='B_drug_vs_vehicle')` reported as \"drug effect\"; reviewer asks about genotype-specific effect.\n\n**Mechanism:** With interaction, `B_drug_vs_vehicle` is drug effect IN THE A REFERENCE LEVEL only, not averaged across A.\n\n**Symptom:** Drug effect doesn't match the marginal estimate from a separate `~ B`-only fit.\n\n**Fix:** Use `~ 0 + group` with combined factor; OR extract per-stratum results explicitly using contrasts that sum main + interaction.\n\n### Pseudoreplication -- 12 samples, only 3 subjects\n\n**Trigger:** 3 subjects x 4 conditions = 12 samples; vanilla DESeq2 with `~ condition`; many DE genes.\n\n**Mechanism:** Same subject contributes multiple observations; not independent. Effective sample size for testing condition is ~3, not 12.\n\n**Symptom:** p-value histogram anti-conservative; replication low.\n\n**Fix:** Include subject in design (`~ subject + condition`) OR use DREAM with random subject.\n\n### Sample swap caught in DE results, not metadata\n\n**Trigger:** PCA shows \"control\" sample clustering with treated; investigation reveals it was mislabeled at thaw.\n\n**Mechanism:** Manual sample tracking is error-prone; cohort >=20 inevitably has swaps.\n\n**Symptom:** One sample dramatically off its group cluster; DE gene list dominated by sample-specific effects.\n\n**Fix:** Run somalier or NGSCheckMate at the matrix-build step, BEFORE DE. Catching a swap early is cheap; finding it post-DE is expensive.\n\n### Sex confounded, chrY genes dominate top hits\n\n**Trigger:** Mixed-sex cohort; sex not in design; PCA shows clear sex split on PC1.\n\n**Mechanism:** Sex distribution differs between groups; \"treatment effect\" partially captures sex.\n\n**Symptom:** Top DE genes are DDX3Y, RPS4Y1, UTY (chrY) and XIST -- not biology of interest.\n\n**Fix:** Add sex to design (`~ sex + condition`). For sex-specific analyses, stratify and report each separately.\n\n### duplicateCorrelation single-pass\n\n**Trigger:** limma user wrote a one-pass `duplicateCorrelation` + lmFit; QC reviewer asks why no re-voom.\n\n**Mechanism:** The proper pattern is: voom -> dupCor -> re-voom WITH correlation -> dupCor again -> lmFit. The first voom doesn't know about block structure; re-voom with correlation gets better weights.\n\n**Symptom:** Slightly inflated DE counts vs the two-pass pattern.\n\n**Fix:** Implement the two-pass pattern per the limma User's Guide (section 9.7).\n\n## Common errors\n\n| Error \u002F symptom | Cause | Fix |\n|-----------------|-------|-----|\n| Sample names don't match between counts and metadata | Underscore\u002Fdash inconsistency, BAM suffix, case | `fuzzy_match_samples()` or manual normalization; report what failed |\n| DESeq2 design not full rank | Confounded covariates | `alias(design)$Complete` to identify; aggregate or drop |\n| `Matrix not positive definite` | High-cardinality batch with few samples | Aggregate batches or use random effect via DREAM |\n| LFC direction reversed | Alphabetical reference level | `relevel()` before `DESeq()` |\n| `results(name='...')` returns drug effect in WT only | Interaction design and naming trap | Use combined factor `~ 0 + group`; or contrast summing main + interaction |\n| Inflated DE list with 12 samples from 3 subjects | Pseudoreplication | Include subject; or use DREAM |\n| Sex effect appears as treatment effect | Sex not in design | Add `~ sex + condition` |\n| Sample distance heatmap shows mixing groups | Likely swap | Run somalier or NGSCheckMate |\n\n## References\n\n- Love MI, Huber W, Anders S. 2014. Moderated estimation of fold change and dispersion for RNA-seq data with DESeq2. *Genome Biol* 15(12):550. doi:10.1186\u002Fs13059-014-0550-8\n- Robinson MD, McCarthy DJ, Smyth GK. 2010. edgeR: a Bioconductor package for differential expression analysis of digital gene expression data. *Bioinformatics* 26(1):139-140. doi:10.1093\u002Fbioinformatics\u002Fbtp616\n- Ritchie ME et al. 2015. limma powers differential expression analyses for RNA-sequencing and microarray studies. *Nucleic Acids Res* 43(7):e47. doi:10.1093\u002Fnar\u002Fgkv007\n- Smyth GK, Michaud J, Scott HS. 2005. Use of within-array replicate spots for assessing differential expression in microarray experiments. *Bioinformatics* 21(9):2067-2075. doi:10.1093\u002Fbioinformatics\u002Fbti270\n- Hoffman GE, Roussos P. 2021. dream: powerful differential expression analysis for repeated measures designs. *Bioinformatics* 37(2):192-201. doi:10.1093\u002Fbioinformatics\u002Fbtaa687\n- Hoffman GE, Schadt EE. 2016. variancePartition: interpreting drivers of variation in complex gene expression studies. *BMC Bioinformatics* 17:483. doi:10.1186\u002Fs12859-016-1323-z\n- Pedersen BS, Bhetariya PJ, Brown J, Kravitz SN, Marth GT, Jensen RL, Bronner MP, Underhill HR, Quinlan AR. 2020. Somalier: rapid relatedness estimation for cancer and germline studies using efficient genome sketches. *Genome Medicine* 12:62. doi:10.1186\u002Fs13073-020-00761-2\n- Lee S, Lee S, Ouellette S, Park W-Y, Lee EA, Park PJ. 2017. NGSCheckMate: software for validating sample identity in next-generation sequencing studies within and across data types. *Nucleic Acids Res* 45(11):e103. doi:10.1093\u002Fnar\u002Fgkx193\n- Mauvais-Jarvis F, Bairey Merz N, Barnes PJ et al. 2020. Sex and gender: modifiers of health, disease, and medicine. *Lancet* 396(10250):565-582. doi:10.1016\u002FS0140-6736(20)31561-0\n\n## Related Skills\n\n- counts-ingest - Building count matrices before metadata join\n- gene-id-mapping - Annotating result tables with symbols\n- normalization - Reference for downstream normalization choice\n- sparse-handling - AnnData obs metadata convention\n- differential-expression\u002Fdeseq2-basics - Where the design formula matters; relevel; interactions\n- differential-expression\u002Fedger-basics - edgeR design matrix conventions\n- differential-expression\u002Fbatch-correction - Design-inclusion vs subtraction; confounding\n- differential-expression\u002Ftimeseries-de - Repeated measures; DREAM mixed model details\n- single-cell\u002Fpreprocessing - scRNA-seq sample metadata handling\n",{"name":5,"source":24,"license":15,"tool_type":25,"description":7,"imported_at":26,"source_path":27,"primary_tool":28,"source_repository":29},"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills","mixed","2026-09-20","expression-matrix\u002Fmetadata-joins\u002FSKILL.md","pandas","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-expression-matrix-metadata-joins","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-expression-matrix-metadata-joins",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-expression-matrix-metadata-joins",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-expression-matrix-metadata-joins","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-expression-matrix-metadata-joins\u002FSKILL.md",true,[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Fjoin_metadata.py","SCRIPT","脚本",1680,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-expression-matrix-metadata-joins\u002Fexamples\u002Fjoin_metadata.py",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"usage-guide.md","REFERENCE","参考文档",7804,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-expression-matrix-metadata-joins\u002Fusage-guide.md",[63,71,78,85,92,99],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":70},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":70},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":70},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":70},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":70},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":70},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]