[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EEY144WQ8YTMTHN18BB4EM":3,"skill-same:01M7EEY144WQ8YTMTHN18BB4EM":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},"01M7EEY144WQ8YTMTHN18BB4EM","bio-population-genetics-plink-basics",null,"Manages PLINK genotype filesets - format conversion (VCF, BED\u002FBIM\u002FFAM, PED\u002FMAP, pgen\u002Fpvar\u002Fpsam) and sample\u002Fvariant QC (missingness, MAF, HWE, sex check, heterozygosity, KING relatedness) with PLINK 1.9 and 2.0. PLINK rewrites allele bookkeeping: PLINK 1.x A1 defaults to the minor allele and is recomputed every load, silently flipping effect-allele meaning unless --keep-allele-order, while PLINK 2.0 tracks explicit REF\u002FALT. QC order matters (variant before sample missingness), HWE is controls-only in 1.9 but not 2.0, add midp, and differential case\u002Fcontrol missingness injects false hits. Use when converting between PLINK formats or running genotype QC before association, structure, or LD analysis. For LD pruning\u002Fclumping see linkage-disequilibrium; for GWAS see association-testing; VCF input from variant-calling\u002Fvcf-basics.","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-population-genetics-plink-basics\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-population-genetics-plink-basics\ndescription: >-\n  Manages PLINK genotype filesets - format conversion (VCF, BED\u002FBIM\u002FFAM, PED\u002FMAP, pgen\u002Fpvar\u002Fpsam) and sample\u002Fvariant QC (missingness, MAF, HWE, sex check, heterozygosity, KING relatedness) with PLINK 1.9 and 2.0. PLINK rewrites allele bookkeeping: PLINK 1.x A1 defaults to the minor allele and is recomputed every load, silently flipping effect-allele meaning unless --keep-allele-order, while PLINK 2.0 tracks explicit REF\u002FALT. QC order matters (variant before sample missingness), HWE is controls-only in 1.9 but not 2.0, add midp, and differential case\u002Fcontrol missingness injects false hits. Use when converting between PLINK formats or running genotype QC before association, structure, or LD analysis. For LD pruning\u002Fclumping see linkage-disequilibrium; for GWAS see association-testing; VCF input from variant-calling\u002Fvcf-basics.\ntool_type: cli\nprimary_tool: plink\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"population-genetics\u002Fplink-basics\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n## Version Compatibility\n\nReference examples tested with: PLINK 1.9 (1.90b7+), PLINK 2.0 (alpha 6+), pandas 2.2+.\n\nBefore using code patterns, verify installed versions match. If versions differ:\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\nVersion traps that change results, not just syntax: PLINK 2.0 `--freq` reports ALT\u002Fnonmajor allele frequency, PLINK 1.9 `--freq` reports MAF. PLINK 2.0 has no `--recode` (use `--export`) and cannot read `.ped\u002F.map` (convert with 1.9 first). PLINK 2.0 `--hwe` is NOT controls-only by default; PLINK 1.9 is. Missing-rate outputs are `.smiss\u002F.vmiss` (2.0) vs `.imiss\u002F.lmiss` (1.9). PLINK 2.0 dropped `--genome`; use `--make-king` for relatedness. The single source of truth for versions is this block, not headings.\n\n# PLINK Basics\n\n**\"Convert my VCF to PLINK and run QC\"** -> Project a VCF into a PLINK fileset and apply sample\u002Fvariant quality filters, holding the allele coding and filter order fixed so downstream effect estimates stay meaningful.\n- CLI: `plink2 --vcf in.vcf.gz --make-pgen` (keeps REF\u002FALT and dosage) or `--make-bed` (biallelic hard calls, A1\u002FA2)\n- CLI: `plink2 --geno 0.02` then `plink2 --mind 0.02 --maf 0.01 --hwe 1e-6 midp` (ordered QC)\n\nScope: PLINK file formats, conversion, and sample\u002Fvariant QC (missingness, MAF, HWE, sex check, heterozygosity, KING relatedness, merging). LD pruning\u002Fclumping (`--indep-pairwise`, `--clump`) route to linkage-disequilibrium; PCA\u002FADMIXTURE to population-structure; `--glm` GWAS to association-testing; VCF generation to variant-calling\u002Fvcf-basics.\n\n## The Single Most Important Insight -- PLINK is a stateful rewriter of allele bookkeeping, not a calculator\n\n1. The most expensive error in the field is trusting that the allele an effect estimate is \"for\" is the allele assumed. PLINK 1.x has no reference allele: it tracks A1 (the counted\u002Feffect allele) and A2, and **A1 defaults to the minor allele, recomputed from the data at load time**. The same SNP flips A1 between two cohorts when the minor allele differs by a few percent, and every `--make-bed` re-derives A2 as the major allele unless `--keep-allele-order` is passed. Betas, odds ratios, and PRS weights are all relative to A1 and become meaningless across cohorts that were not harmonized.\n2. PLINK 2.0 fixed the **design** by tracking explicit REF\u002FALT in `.pvar` (REF is the genuine reference base; the counted allele for `--glm` is set independently), but exporting back to `.bed` collapses into the A1\u002FA2 world and re-inherits the trap.\n3. Pinning alleles to a fixed reference (`--ref-allele`\u002F`--a1-allele` from a file, `--ref-from-fa`, or staying in `.pgen`) plus `--keep-allele-order` on any `.bed` export is the line between reproducible and quietly-wrong analysis.\n4. Two QC choices silently corrupt association before any test is run: filter **order** (sample-vs-variant missingness) and the **case\u002Fcontrol missingness confounder**. Both are covered below.\n\n## Tool Taxonomy -- PLINK 1.9 vs PLINK 2.0\n\n| Axis | PLINK 1.9 (`plink`) | PLINK 2.0 (`plink2`) |\n|------|---------------------|----------------------|\n| Status \u002F model | Stable, feature-frozen; hard calls only; A1\u002FA2 | Active; hard calls and dosages; explicit REF\u002FALT, multiallelic-aware |\n| Native format | `.bed\u002F.bim\u002F.fam` | `.pgen\u002F.pvar\u002F.psam` |\n| Allele bookkeeping | A1 = minor by default (the trap) | REF\u002FALT tracked; counted allele explicit |\n| PED\u002FMAP (`--file`) | Yes | No (convert via 1.9) |\n| IBD `--genome` \u002F `--cluster` | Yes | No (use 1.9 or KING) |\n| KING-robust relatedness | No | `--make-king`, `--king-cutoff` |\n| Multi-fileset merge | `--bmerge` \u002F `--merge-list` (battle-tested) | `--pmerge` \u002F `--pmerge-list` (newer) |\n| HWE default | controls-only | NOT controls-only |\n| `--freq` default | MAF | ALT\u002Fnonmajor frequency |\n| Missing-rate output | `.imiss` \u002F `.lmiss` | `.smiss` \u002F `.vmiss` |\n| Speed\u002Fmemory at biobank N | baseline | substantially faster, lower memory |\n\n## Decision Tree by Scenario\n\n| Scenario | Use | Why |\n|----------|-----|-----|\n| Imputed data with dosage uncertainty | plink2 `.pgen` | 1.9 hard-calls and discards dosage |\n| Relatedness in a structured\u002Fmulti-ancestry sample | plink2 `--make-king` | PI_HAT (`--genome`) is biased under structure; KING gives negative kinship for cross-ancestry unrelateds |\n| Classic multi-dataset merge | plink1.9 `--bmerge`\u002F`--merge-list` | most documented and predictable path |\n| IBD `--genome` \u002F IBS `--cluster` | plink1.9 | plink2 dropped these |\n| Reading PED\u002FMAP or Affymetrix-era text | plink1.9 `--file` | plink2 cannot read them |\n| Big modern QC\u002Fassociation\u002FPCA inputs | plink2, export `.bed` last | speed plus correct allele handling; minimize time in A1\u002FA2 land |\n| Default working format | stay in `.pgen` through QC | keeps REF\u002FALT honest; export `.bed` only when a tool demands it (then `--keep-allele-order`) |\n\n## File Formats\n\n| Binary (1.9) | Contents | PLINK 2.0 | Contents |\n|------|----------|-----------|----------|\n| `.bed` | binary hard-call genotypes (biallelic only) | `.pgen` | genotypes + dosages, multiallelic-aware |\n| `.bim` | variant info (chr, ID, cM, pos, **A1, A2**) | `.pvar` | variant info with genuine **REF\u002FALT** |\n| `.fam` | sample info (FID, IID, father, mother, sex, pheno) | `.psam` | sample info |\n\nText `.ped\u002F.map` (PLINK 1.9 `--file`) is legacy; convert to binary once and work from there.\n\n## Format Conversion\n\n```bash\n# VCF -> PLINK. --make-pgen preserves REF\u002FALT and dosage; --make-bed collapses to A1\u002FA2 hard calls.\nplink2 --vcf in.vcf.gz --make-pgen --out data            # preferred working format\nplink2 --vcf in.vcf.gz --double-id --make-bed --out data # biallelic hard calls; --double-id copies the VCF sample name into both FID and IID\n\n# Keep the reference allele honest when leaving pgen for bed (otherwise A2 is re-set to major):\nplink2 --pfile data --ref-from-fa --fa GRCh38.fa --make-bed --keep-allele-order --out data_bed\n\n# PLINK -> VCF. plink2 uses --export (no --recode); add bgz to compress.\nplink2 --bfile data --export vcf bgz --out out\nplink  --bfile data --recode vcf --out out               # PLINK 1.9 idiom\n\n# PED\u002FMAP must be read by PLINK 1.9; plink2 cannot.\nplink --file textdata --make-bed --out data\n```\n\nMultiallelic sites cannot live in `.bed` (biallelic by construction). Split first with `bcftools norm -m-` or accept plink2's split, and track which records changed. Strand-flip logic cannot operate on indels; `--snps-only just-acgt` removes them when needed.\n\n## Quality Control Filtering\n\n```bash\n# Variant missingness FIRST, in its own run, so a sample is not dropped for missingness driven by variants slated for removal.\nplink2 --pfile data --geno 0.02 --make-pgen --out step1     # default --geno is 0.1; GWAS QC tightens to 0.02-0.05\n\n# THEN sample missingness, MAF, and HWE on the surviving variants.\nplink2 --pfile step1 --mind 0.02 --maf 0.01 --hwe 1e-6 midp --make-pgen --out step2\n```\n\nHWE caveats that change which variants survive:\n- `midp` is not optional. The plain exact test is discrete and conservative for low-count genotypes, biasing toward retaining variants with missing data; mid-p brings rejection to nominal (Graffelman 2013).\n- **Apply HWE to controls only.** A true risk variant depletes heterozygotes in cases and would fail a case-inclusive HWE test and be wrongly removed. PLINK 1.9 does this automatically; override with the `include-nonctrl` modifier. **plink2 does NOT** - replicate the behavior with `--keep-if \"PHENO1 == control\"` before `--hwe`, or the rewrite over-filters real associations.\n- In a structured sample the Wahlund effect reduces heterozygosity, so a two-sided HWE filter drops real variants; many genotyping artifacts (contamination, paralog mismapping) instead inflate heterozygosity, so under structure a one-sided excess-het filter (plink2 `keep-fewhet`) avoids dropping Wahlund-deficient real variants.\n\n```bash\n# Differential missingness: a top source of false GWAS hits. A variant genotyped less well in cases than controls\n# correlates missingness with phenotype; a flat --geno keeps it and injects association.\nplink2 --bfile data --pheno pheno.txt --test-missing --out diffmiss   # drop variants with case\u002Fcontrol missingness skew\n```\n\n## Sample QC\n\n```bash\n# Sex check. Split the pseudoautosomal region FIRST or male PAR heterozygosity reads as a sex error.\nplink2 --bfile data --split-par hg38 --check-sex --out sexcheck   # PLINK 1.9 uses --split-x hg38\n# Default calls: F \u003C 0.2 -> female, F > 0.8 -> male, between -> PROBLEM. These ~2007 defaults are often wrong\n# for modern arrays; plot the F histogram and re-pick thresholds at the gap between the two clumps.\n\n# Heterozygosity outliers, on LD-pruned MAF-filtered SNPs only (raw data is dominated by a few regions).\nplink2 --bfile data_pruned --het --out het   # flag |F - cohort_mean| > 3 SD: excess het = contamination, deficit = inbreeding\u002Fdup\n\n# Relatedness. KING-robust is structure-robust; PI_HAT (--genome) is not.\nplink2 --bfile data --make-king-table --out king\nplink2 --bfile data --king-cutoff 0.0884 --out unrelated   # prune to no-closer-than 2nd-degree (dup 0.354, 1st 0.177, 2nd 0.0884)\n```\n\n`--check-sex` and heterozygosity outliers usually signal a sample swap or contamination, not biology - investigate the sample before dropping it. KING uses autosomes only; the same negative bias that makes cross-ancestry unrelated pairs read below zero also pulls true cross-ancestry relatives toward zero, so KING UNDER-detects relatives in admixed or multi-ancestry cohorts (use PC-Relate \u002F PC-AiR there, out of scope here).\n\n## Merging Datasets\n\n```bash\nplink --bfile data1 --bmerge data2 --make-bed --out merged\n# Aborts with a \"3+ alleles\" error when the same SNP is on opposite strands (A\u002FG vs T\u002FC). Flip the offenders, then retry:\nplink --bfile data2 --flip merged-merge.missnp --make-bed --out data2_flipped\n```\n\n`--flip` swaps A\u003C->T and C\u003C->G only and **cannot disambiguate palindromic A\u002FT and C\u002FG SNPs** (identical on both strands) - resolve those by allele frequency or drop them. Harmonize variant IDs to `chr:pos:ref:alt` (`--set-all-var-ids @:#:\\$r:\\$a`) before merging so the key is positional and allele-aware, not rsID-collision-prone. Build mismatch (hg19 vs hg38) requires liftover first, which can itself flip strand in inverted regions.\n\n## Per-Operation Failure Modes\n\n### A1\u002FA2 effect-allele flip\n**Trigger:** `--make-bed` without `--keep-allele-order`, or merging two cohorts. **Mechanism:** A1 is re-derived as the minor allele from whatever data is present. **Symptom:** betas\u002FORs\u002FPRS weights point at the wrong allele; meta-analysis cancels true signal. **Fix:** `--keep-allele-order` on every `.bed` export and pin alleles from a fixed reference (`--ref-from-fa` \u002F `--a1-allele`).\n\n### Wrong QC order\n**Trigger:** `--geno` and `--mind` in one command. **Mechanism:** plink applies `--mind` (sample) before `--geno` (variant) in a single run; published QC wants variants dropped first. **Symptom:** good samples removed for missingness caused by variants that were about to be filtered. **Fix:** run `--geno` and `--mind` in separate invocations, variant filter first.\n\n### Differential missingness\n**Trigger:** case\u002Fcontrol cohorts genotyped in separate batches. **Mechanism:** missingness correlates with phenotype; a flat `--geno` retains the variant. **Symptom:** false genome-wide hits at batch-skewed sites. **Fix:** `--test-missing` and drop variants with case\u002Fcontrol missingness skew, not just a global `--geno`.\n\n### Phenotype encoding inversion\n**Trigger:** loading a 0\u002F1 case\u002Fcontrol file without `--1`. **Mechanism:** PLINK reads `1`=control, `2`=case, `0`\u002F`-9`=missing by default; a 0\u002F1 file makes every case read as control and every control as missing. **Symptom:** silent, total phenotype corruption; null or inverted GWAS. **Fix:** `--1` for 0\u002F1 coding; any value outside {-9,0,1,2} is treated as quantitative.\n\n### PAR not split before sex\u002FX analysis\n**Trigger:** `--check-sex` or X-specific work without `--split-par`\u002F`--split-x`. **Mechanism:** male PAR is diploid and heterozygous; uncoded it looks like X het. **Symptom:** males mis-called female; spurious sex PROBLEMs. **Fix:** `--split-par \u003Cbuild>` with the correct genome build (hg19 vs hg38 boundaries differ).\n\n## Quantitative Thresholds\n\n| Operation | Flag | Typical value | Rationale |\n|-----------|------|---------------|-----------|\n| Variant missingness | `--geno` | 0.02 (PCA\u002Fstructure), 0.05 (standard) | default 0.1; >2-5% missing flags batch artifacts |\n| Sample missingness | `--mind` | 0.02-0.05 | default 0.1; apply AFTER `--geno` |\n| MAF | `--maf` | 0.01 (common-variant GWAS), 0.05 (PCA), down to 0.001 at large N | below ~0.01 power and HWE\u002Fsex-check stability collapse |\n| HWE | `--hwe ... midp` | 1e-6 controls-only | loose vs association: screens artifacts, not biology |\n| Sex F | `--check-sex` | female \u003C0.2, male >0.8 (default) | re-pick from the F histogram gap |\n| Heterozygosity | `--het` | \\|F - mean\\| > 3 SD | excess het = contamination, deficit = inbreeding\u002Fdup; on LD-pruned SNPs |\n| Relatedness (KING) | `--king-cutoff` | 0.0884 (2nd-deg+), 0.177 (1st), 0.354 (dup\u002FMZ cutoff; a true MZ\u002Fdup pair sits at ~0.5) | KING boundaries, Manichaikul 2010 |\n\nThresholds are conventions, not laws - inspect the distributions and verify current best practice before applying numbers blindly.\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| `--hwe-all` \"unrecognized flag\" | flag does not exist | controls-only override is `include-nonctrl` (1.9); plink2 needs `--keep-if \"PHENO1 == control\"` |\n| HWE over-filters real associations | assuming plink2 `--hwe` is controls-only | it is not; gate to controls first; always add `midp` |\n| ALT_FREQ read as MAF | plink2 `--freq` reports ALT frequency | inspect columns; PLINK 1.9 `--freq` reports MAF |\n| Script reads empty missingness file | wrong suffix | 2.0 `.smiss\u002F.vmiss`, 1.9 `.imiss\u002F.lmiss` |\n| `--keep-fam sample_id` keeps nothing | `--keep-fam` takes a FILE of FIDs | use `--keep` with a FID IID file |\n| Frequencies use a subset in family data | MAF\u002FHWE\u002F`--freq` are founders-only | add `--nonfounders` if intended |\n| Duplicate variant IDs break `--extract`\u002Fmerge | duplicate IDs | `--rm-dup force-first` or set `chr:pos:ref:alt` IDs |\n\n## References\n\n1. Purcell S, et al. PLINK: a tool set for whole-genome association and population-based linkage analyses. American Journal of Human Genetics 2007; 81(3):559-575. DOI:10.1086\u002F519795.\n2. Chang CC, Chow CC, Tellier LCAM, Vattikuti S, Purcell SM, Lee JJ. Second-generation PLINK: rising to the challenge of larger and richer datasets. GigaScience 2015; 4:7. DOI:10.1186\u002Fs13742-015-0047-8.\n3. Manichaikul A, Mychaleckyj JC, Rich SS, Daly K, Sale M, Chen W-M. Robust relationship inference in genome-wide association studies. Bioinformatics 2010; 26(22):2867-2873. DOI:10.1093\u002Fbioinformatics\u002Fbtq559.\n4. Wigginton JE, Cutler DJ, Abecasis GR. A note on exact tests of Hardy-Weinberg equilibrium. American Journal of Human Genetics 2005; 76(5):887-893. DOI:10.1086\u002F429864.\n5. Graffelman J, Moreno V. The mid p-value in exact tests for Hardy-Weinberg equilibrium. Statistical Applications in Genetics and Molecular Biology 2013; 12(4):433-448. DOI:10.1515\u002Fsagmb-2012-0039.\n\n## Related Skills\n\n- linkage-disequilibrium - LD pruning and clumping on QC'd genotypes\n- population-structure - PCA and ADMIXTURE after QC and relatedness pruning\n- association-testing - GWAS with `--glm` on the filtered fileset\n- variant-calling\u002Fvcf-basics - VCF generation and manipulation before conversion\n- phasing-imputation\u002Fgenotype-imputation - imputed dosages that enter as `.pgen`\n","## Version Compatibility\n\nReference examples tested with: PLINK 1.9 (1.90b7+), PLINK 2.0 (alpha 6+), pandas 2.2+.\n\nBefore using code patterns, verify installed versions match. If versions differ:\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\nVersion traps that change results, not just syntax: PLINK 2.0 `--freq` reports ALT\u002Fnonmajor allele frequency, PLINK 1.9 `--freq` reports MAF. PLINK 2.0 has no `--recode` (use `--export`) and cannot read `.ped\u002F.map` (convert with 1.9 first). PLINK 2.0 `--hwe` is NOT controls-only by default; PLINK 1.9 is. Missing-rate outputs are `.smiss\u002F.vmiss` (2.0) vs `.imiss\u002F.lmiss` (1.9). PLINK 2.0 dropped `--genome`; use `--make-king` for relatedness. The single source of truth for versions is this block, not headings.\n\n# PLINK Basics\n\n**\"Convert my VCF to PLINK and run QC\"** -> Project a VCF into a PLINK fileset and apply sample\u002Fvariant quality filters, holding the allele coding and filter order fixed so downstream effect estimates stay meaningful.\n- CLI: `plink2 --vcf in.vcf.gz --make-pgen` (keeps REF\u002FALT and dosage) or `--make-bed` (biallelic hard calls, A1\u002FA2)\n- CLI: `plink2 --geno 0.02` then `plink2 --mind 0.02 --maf 0.01 --hwe 1e-6 midp` (ordered QC)\n\nScope: PLINK file formats, conversion, and sample\u002Fvariant QC (missingness, MAF, HWE, sex check, heterozygosity, KING relatedness, merging). LD pruning\u002Fclumping (`--indep-pairwise`, `--clump`) route to linkage-disequilibrium; PCA\u002FADMIXTURE to population-structure; `--glm` GWAS to association-testing; VCF generation to variant-calling\u002Fvcf-basics.\n\n## The Single Most Important Insight -- PLINK is a stateful rewriter of allele bookkeeping, not a calculator\n\n1. The most expensive error in the field is trusting that the allele an effect estimate is \"for\" is the allele assumed. PLINK 1.x has no reference allele: it tracks A1 (the counted\u002Feffect allele) and A2, and **A1 defaults to the minor allele, recomputed from the data at load time**. The same SNP flips A1 between two cohorts when the minor allele differs by a few percent, and every `--make-bed` re-derives A2 as the major allele unless `--keep-allele-order` is passed. Betas, odds ratios, and PRS weights are all relative to A1 and become meaningless across cohorts that were not harmonized.\n2. PLINK 2.0 fixed the **design** by tracking explicit REF\u002FALT in `.pvar` (REF is the genuine reference base; the counted allele for `--glm` is set independently), but exporting back to `.bed` collapses into the A1\u002FA2 world and re-inherits the trap.\n3. Pinning alleles to a fixed reference (`--ref-allele`\u002F`--a1-allele` from a file, `--ref-from-fa`, or staying in `.pgen`) plus `--keep-allele-order` on any `.bed` export is the line between reproducible and quietly-wrong analysis.\n4. Two QC choices silently corrupt association before any test is run: filter **order** (sample-vs-variant missingness) and the **case\u002Fcontrol missingness confounder**. Both are covered below.\n\n## Tool Taxonomy -- PLINK 1.9 vs PLINK 2.0\n\n| Axis | PLINK 1.9 (`plink`) | PLINK 2.0 (`plink2`) |\n|------|---------------------|----------------------|\n| Status \u002F model | Stable, feature-frozen; hard calls only; A1\u002FA2 | Active; hard calls and dosages; explicit REF\u002FALT, multiallelic-aware |\n| Native format | `.bed\u002F.bim\u002F.fam` | `.pgen\u002F.pvar\u002F.psam` |\n| Allele bookkeeping | A1 = minor by default (the trap) | REF\u002FALT tracked; counted allele explicit |\n| PED\u002FMAP (`--file`) | Yes | No (convert via 1.9) |\n| IBD `--genome` \u002F `--cluster` | Yes | No (use 1.9 or KING) |\n| KING-robust relatedness | No | `--make-king`, `--king-cutoff` |\n| Multi-fileset merge | `--bmerge` \u002F `--merge-list` (battle-tested) | `--pmerge` \u002F `--pmerge-list` (newer) |\n| HWE default | controls-only | NOT controls-only |\n| `--freq` default | MAF | ALT\u002Fnonmajor frequency |\n| Missing-rate output | `.imiss` \u002F `.lmiss` | `.smiss` \u002F `.vmiss` |\n| Speed\u002Fmemory at biobank N | baseline | substantially faster, lower memory |\n\n## Decision Tree by Scenario\n\n| Scenario | Use | Why |\n|----------|-----|-----|\n| Imputed data with dosage uncertainty | plink2 `.pgen` | 1.9 hard-calls and discards dosage |\n| Relatedness in a structured\u002Fmulti-ancestry sample | plink2 `--make-king` | PI_HAT (`--genome`) is biased under structure; KING gives negative kinship for cross-ancestry unrelateds |\n| Classic multi-dataset merge | plink1.9 `--bmerge`\u002F`--merge-list` | most documented and predictable path |\n| IBD `--genome` \u002F IBS `--cluster` | plink1.9 | plink2 dropped these |\n| Reading PED\u002FMAP or Affymetrix-era text | plink1.9 `--file` | plink2 cannot read them |\n| Big modern QC\u002Fassociation\u002FPCA inputs | plink2, export `.bed` last | speed plus correct allele handling; minimize time in A1\u002FA2 land |\n| Default working format | stay in `.pgen` through QC | keeps REF\u002FALT honest; export `.bed` only when a tool demands it (then `--keep-allele-order`) |\n\n## File Formats\n\n| Binary (1.9) | Contents | PLINK 2.0 | Contents |\n|------|----------|-----------|----------|\n| `.bed` | binary hard-call genotypes (biallelic only) | `.pgen` | genotypes + dosages, multiallelic-aware |\n| `.bim` | variant info (chr, ID, cM, pos, **A1, A2**) | `.pvar` | variant info with genuine **REF\u002FALT** |\n| `.fam` | sample info (FID, IID, father, mother, sex, pheno) | `.psam` | sample info |\n\nText `.ped\u002F.map` (PLINK 1.9 `--file`) is legacy; convert to binary once and work from there.\n\n## Format Conversion\n\n```bash\n# VCF -> PLINK. --make-pgen preserves REF\u002FALT and dosage; --make-bed collapses to A1\u002FA2 hard calls.\nplink2 --vcf in.vcf.gz --make-pgen --out data            # preferred working format\nplink2 --vcf in.vcf.gz --double-id --make-bed --out data # biallelic hard calls; --double-id copies the VCF sample name into both FID and IID\n\n# Keep the reference allele honest when leaving pgen for bed (otherwise A2 is re-set to major):\nplink2 --pfile data --ref-from-fa --fa GRCh38.fa --make-bed --keep-allele-order --out data_bed\n\n# PLINK -> VCF. plink2 uses --export (no --recode); add bgz to compress.\nplink2 --bfile data --export vcf bgz --out out\nplink  --bfile data --recode vcf --out out               # PLINK 1.9 idiom\n\n# PED\u002FMAP must be read by PLINK 1.9; plink2 cannot.\nplink --file textdata --make-bed --out data\n```\n\nMultiallelic sites cannot live in `.bed` (biallelic by construction). Split first with `bcftools norm -m-` or accept plink2's split, and track which records changed. Strand-flip logic cannot operate on indels; `--snps-only just-acgt` removes them when needed.\n\n## Quality Control Filtering\n\n```bash\n# Variant missingness FIRST, in its own run, so a sample is not dropped for missingness driven by variants slated for removal.\nplink2 --pfile data --geno 0.02 --make-pgen --out step1     # default --geno is 0.1; GWAS QC tightens to 0.02-0.05\n\n# THEN sample missingness, MAF, and HWE on the surviving variants.\nplink2 --pfile step1 --mind 0.02 --maf 0.01 --hwe 1e-6 midp --make-pgen --out step2\n```\n\nHWE caveats that change which variants survive:\n- `midp` is not optional. The plain exact test is discrete and conservative for low-count genotypes, biasing toward retaining variants with missing data; mid-p brings rejection to nominal (Graffelman 2013).\n- **Apply HWE to controls only.** A true risk variant depletes heterozygotes in cases and would fail a case-inclusive HWE test and be wrongly removed. PLINK 1.9 does this automatically; override with the `include-nonctrl` modifier. **plink2 does NOT** - replicate the behavior with `--keep-if \"PHENO1 == control\"` before `--hwe`, or the rewrite over-filters real associations.\n- In a structured sample the Wahlund effect reduces heterozygosity, so a two-sided HWE filter drops real variants; many genotyping artifacts (contamination, paralog mismapping) instead inflate heterozygosity, so under structure a one-sided excess-het filter (plink2 `keep-fewhet`) avoids dropping Wahlund-deficient real variants.\n\n```bash\n# Differential missingness: a top source of false GWAS hits. A variant genotyped less well in cases than controls\n# correlates missingness with phenotype; a flat --geno keeps it and injects association.\nplink2 --bfile data --pheno pheno.txt --test-missing --out diffmiss   # drop variants with case\u002Fcontrol missingness skew\n```\n\n## Sample QC\n\n```bash\n# Sex check. Split the pseudoautosomal region FIRST or male PAR heterozygosity reads as a sex error.\nplink2 --bfile data --split-par hg38 --check-sex --out sexcheck   # PLINK 1.9 uses --split-x hg38\n# Default calls: F \u003C 0.2 -> female, F > 0.8 -> male, between -> PROBLEM. These ~2007 defaults are often wrong\n# for modern arrays; plot the F histogram and re-pick thresholds at the gap between the two clumps.\n\n# Heterozygosity outliers, on LD-pruned MAF-filtered SNPs only (raw data is dominated by a few regions).\nplink2 --bfile data_pruned --het --out het   # flag |F - cohort_mean| > 3 SD: excess het = contamination, deficit = inbreeding\u002Fdup\n\n# Relatedness. KING-robust is structure-robust; PI_HAT (--genome) is not.\nplink2 --bfile data --make-king-table --out king\nplink2 --bfile data --king-cutoff 0.0884 --out unrelated   # prune to no-closer-than 2nd-degree (dup 0.354, 1st 0.177, 2nd 0.0884)\n```\n\n`--check-sex` and heterozygosity outliers usually signal a sample swap or contamination, not biology - investigate the sample before dropping it. KING uses autosomes only; the same negative bias that makes cross-ancestry unrelated pairs read below zero also pulls true cross-ancestry relatives toward zero, so KING UNDER-detects relatives in admixed or multi-ancestry cohorts (use PC-Relate \u002F PC-AiR there, out of scope here).\n\n## Merging Datasets\n\n```bash\nplink --bfile data1 --bmerge data2 --make-bed --out merged\n# Aborts with a \"3+ alleles\" error when the same SNP is on opposite strands (A\u002FG vs T\u002FC). Flip the offenders, then retry:\nplink --bfile data2 --flip merged-merge.missnp --make-bed --out data2_flipped\n```\n\n`--flip` swaps A\u003C->T and C\u003C->G only and **cannot disambiguate palindromic A\u002FT and C\u002FG SNPs** (identical on both strands) - resolve those by allele frequency or drop them. Harmonize variant IDs to `chr:pos:ref:alt` (`--set-all-var-ids @:#:\\$r:\\$a`) before merging so the key is positional and allele-aware, not rsID-collision-prone. Build mismatch (hg19 vs hg38) requires liftover first, which can itself flip strand in inverted regions.\n\n## Per-Operation Failure Modes\n\n### A1\u002FA2 effect-allele flip\n**Trigger:** `--make-bed` without `--keep-allele-order`, or merging two cohorts. **Mechanism:** A1 is re-derived as the minor allele from whatever data is present. **Symptom:** betas\u002FORs\u002FPRS weights point at the wrong allele; meta-analysis cancels true signal. **Fix:** `--keep-allele-order` on every `.bed` export and pin alleles from a fixed reference (`--ref-from-fa` \u002F `--a1-allele`).\n\n### Wrong QC order\n**Trigger:** `--geno` and `--mind` in one command. **Mechanism:** plink applies `--mind` (sample) before `--geno` (variant) in a single run; published QC wants variants dropped first. **Symptom:** good samples removed for missingness caused by variants that were about to be filtered. **Fix:** run `--geno` and `--mind` in separate invocations, variant filter first.\n\n### Differential missingness\n**Trigger:** case\u002Fcontrol cohorts genotyped in separate batches. **Mechanism:** missingness correlates with phenotype; a flat `--geno` retains the variant. **Symptom:** false genome-wide hits at batch-skewed sites. **Fix:** `--test-missing` and drop variants with case\u002Fcontrol missingness skew, not just a global `--geno`.\n\n### Phenotype encoding inversion\n**Trigger:** loading a 0\u002F1 case\u002Fcontrol file without `--1`. **Mechanism:** PLINK reads `1`=control, `2`=case, `0`\u002F`-9`=missing by default; a 0\u002F1 file makes every case read as control and every control as missing. **Symptom:** silent, total phenotype corruption; null or inverted GWAS. **Fix:** `--1` for 0\u002F1 coding; any value outside {-9,0,1,2} is treated as quantitative.\n\n### PAR not split before sex\u002FX analysis\n**Trigger:** `--check-sex` or X-specific work without `--split-par`\u002F`--split-x`. **Mechanism:** male PAR is diploid and heterozygous; uncoded it looks like X het. **Symptom:** males mis-called female; spurious sex PROBLEMs. **Fix:** `--split-par \u003Cbuild>` with the correct genome build (hg19 vs hg38 boundaries differ).\n\n## Quantitative Thresholds\n\n| Operation | Flag | Typical value | Rationale |\n|-----------|------|---------------|-----------|\n| Variant missingness | `--geno` | 0.02 (PCA\u002Fstructure), 0.05 (standard) | default 0.1; >2-5% missing flags batch artifacts |\n| Sample missingness | `--mind` | 0.02-0.05 | default 0.1; apply AFTER `--geno` |\n| MAF | `--maf` | 0.01 (common-variant GWAS), 0.05 (PCA), down to 0.001 at large N | below ~0.01 power and HWE\u002Fsex-check stability collapse |\n| HWE | `--hwe ... midp` | 1e-6 controls-only | loose vs association: screens artifacts, not biology |\n| Sex F | `--check-sex` | female \u003C0.2, male >0.8 (default) | re-pick from the F histogram gap |\n| Heterozygosity | `--het` | \\|F - mean\\| > 3 SD | excess het = contamination, deficit = inbreeding\u002Fdup; on LD-pruned SNPs |\n| Relatedness (KING) | `--king-cutoff` | 0.0884 (2nd-deg+), 0.177 (1st), 0.354 (dup\u002FMZ cutoff; a true MZ\u002Fdup pair sits at ~0.5) | KING boundaries, Manichaikul 2010 |\n\nThresholds are conventions, not laws - inspect the distributions and verify current best practice before applying numbers blindly.\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| `--hwe-all` \"unrecognized flag\" | flag does not exist | controls-only override is `include-nonctrl` (1.9); plink2 needs `--keep-if \"PHENO1 == control\"` |\n| HWE over-filters real associations | assuming plink2 `--hwe` is controls-only | it is not; gate to controls first; always add `midp` |\n| ALT_FREQ read as MAF | plink2 `--freq` reports ALT frequency | inspect columns; PLINK 1.9 `--freq` reports MAF |\n| Script reads empty missingness file | wrong suffix | 2.0 `.smiss\u002F.vmiss`, 1.9 `.imiss\u002F.lmiss` |\n| `--keep-fam sample_id` keeps nothing | `--keep-fam` takes a FILE of FIDs | use `--keep` with a FID IID file |\n| Frequencies use a subset in family data | MAF\u002FHWE\u002F`--freq` are founders-only | add `--nonfounders` if intended |\n| Duplicate variant IDs break `--extract`\u002Fmerge | duplicate IDs | `--rm-dup force-first` or set `chr:pos:ref:alt` IDs |\n\n## References\n\n1. Purcell S, et al. PLINK: a tool set for whole-genome association and population-based linkage analyses. American Journal of Human Genetics 2007; 81(3):559-575. DOI:10.1086\u002F519795.\n2. Chang CC, Chow CC, Tellier LCAM, Vattikuti S, Purcell SM, Lee JJ. Second-generation PLINK: rising to the challenge of larger and richer datasets. GigaScience 2015; 4:7. DOI:10.1186\u002Fs13742-015-0047-8.\n3. Manichaikul A, Mychaleckyj JC, Rich SS, Daly K, Sale M, Chen W-M. Robust relationship inference in genome-wide association studies. Bioinformatics 2010; 26(22):2867-2873. DOI:10.1093\u002Fbioinformatics\u002Fbtq559.\n4. Wigginton JE, Cutler DJ, Abecasis GR. A note on exact tests of Hardy-Weinberg equilibrium. American Journal of Human Genetics 2005; 76(5):887-893. DOI:10.1086\u002F429864.\n5. Graffelman J, Moreno V. The mid p-value in exact tests for Hardy-Weinberg equilibrium. Statistical Applications in Genetics and Molecular Biology 2013; 12(4):433-448. DOI:10.1515\u002Fsagmb-2012-0039.\n\n## Related Skills\n\n- linkage-disequilibrium - LD pruning and clumping on QC'd genotypes\n- population-structure - PCA and ADMIXTURE after QC and relatedness pruning\n- association-testing - GWAS with `--glm` on the filtered fileset\n- variant-calling\u002Fvcf-basics - VCF generation and manipulation before conversion\n- phasing-imputation\u002Fgenotype-imputation - imputed dosages that enter as `.pgen`\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","cli","2026-09-20","population-genetics\u002Fplink-basics\u002FSKILL.md","plink","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-population-genetics-plink-basics","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-population-genetics-plink-basics",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-population-genetics-plink-basics",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-population-genetics-plink-basics","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-population-genetics-plink-basics\u002FSKILL.md",true,[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Fqc_pipeline.sh","SCRIPT","脚本",2689,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-population-genetics-plink-basics\u002Fexamples\u002Fqc_pipeline.sh",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"usage-guide.md","REFERENCE","参考文档",4543,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-population-genetics-plink-basics\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",[],[]]