---
title: "Module 4: Variant quality control"
format:
  html:
    toc: true
    toc-depth: 2
    toc-title: "Contents"
    toc-location: left
    toc-expand: true
    anchor-sections: true
    code-copy: true
    code-fold: false
    code-overflow: wrap
    embed-resources: true
    include-after-body:
      text: |
        <script>
        document.querySelectorAll('a[href$=".qmd"]').forEach(function (a) {
          a.setAttribute('href', a.getAttribute('href').replace(/[.]qmd$/, '.html'));
        });
        </script>
editor: visual
editor_options:
  chunk_output_type: console
course_source_sha256: "590070cd5b754eb36f8d6fc9676a68e9bde1ea6bbab901085bdfa496a35008cd"
---

Open `GWAS_course.Rproj` and work from the project root. Run the chunks in order in a fresh R session.
All data are simulated. Read each summary, run its chunk and compare your result with the expected result.
The linked step pages explain the ideas and provide troubleshooting.

::: {.callout-note title="In this module"}

**Time.** About 45 minutes.

**Before you start.** You need the full [checkpoint at step 3.8](https://www.manuelgentiluomo.it/teaching/gwas/module-3/step-3-8). The first code chunk checks the files that this module needs.

**Steps.**

- [4.1 Variant call rate](#step-4-1)
- [4.2 Differential missingness](#step-4-2)
- [4.3 Allele frequency](#step-4-3)
- [4.4 Hardy-Weinberg and sample size](#step-4-4)
- [4.5 Sex chromosomes, MT and duplicated sites](#step-4-5)
- [4.6 Variant QC summary and checkpoint](#step-4-6)

**Where the module ends.** The checkpoint at step 4.6.

:::

```{r}
#| label: module4_check
if (!file.exists("config.R") && file.exists("../config.R")) setwd("..")
source("R/guided.R"); guided_check_module(4)
```

```{r}
#| label: module4_setup
source("R/guided.R")
cfg <- guided_init()
```

## Step 4.1 · Variant call rate {#step-4-1}

We remove variants with more than 2% of their results missing. This keeps sites in the DNA with results for at least 98% of the remaining people.

[Read step 4.1 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-4/step-4-1).

```{r}
#| label: s4-1
run_plink(cfg, c("--pfile", guided_path(cfg, "3.8"), "--geno", "0.02", "--make-pgen", "--out", guided_path(cfg, "4.1")))  # <1>
# Course bookkeeping: records the counts for the next step. Do not change.
ops <- guided_replay_lists(cfg, "4.1", "3.8")
guided_register(cfg, "4.1", "3.8", 1844, 295559, operations = ops)
```

1. Remove variants with more than 2% of their results missing.

### What each option does

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM files named results/guided/s3-8_state. |
| `--geno` | Removes variants with more than 2% of their genotype calls missing. |
| `--make-pgen` | Saves the remaining data as PGEN, PVAR and PSAM files. |
| `--out` | Starts the output file names with results/guided/s4-1_state. |

Every command also uses `--threads 2` (PLINK runs at most two tasks at the same time) and `--memory 2048` (PLINK uses at most about 2 GB of memory).

::: {.callout-tip title="Expected result" collapse="true"}

801 variants are removed. This is not exactly the 800 planted low-call variants. 1,844 samples and 295,559 variants remain.

:::

::: {.callout-note title="PLINK terminal equivalent"}

These commands are shown for reference. Run the R chunk above to follow the course.
R creates any lists needed between PLINK commands. On Windows, use `bin\plink2.exe`.

```sh
bin/plink2 --pfile results/guided/s3-8_state --geno 0.02 --make-pgen --out results/guided/s4-1_state --threads 2 --memory 2048
```

:::

::: {.callout-tip title="Try other thresholds (optional)" collapse="true"}

This box is not part of the main path. No later step uses it. It does not change your results.

At this step `--geno 0.02` removes variants with more than 2% missing calls in the samples that remain. A strict limit removes more variants, but each variant that stays has more complete data. A generous limit keeps more variants with more missing calls. Missing calls that depend on the disease status can create false associations, which is why a clear limit matters. Each trial starts from the cohort saved at 3.8 and changes the limit only.

```{r}
#| label: s4-1_thresholds
#| eval: false
# Optional. Each trial starts from the same input and changes one threshold only.
thresholds <- c(0.01, 0.02, 0.05, 0.10, 0.20)
trial <- threshold_counts(cfg, guided_path(cfg, "3.8"), "--geno", thresholds)
trial$course_value <- trial$threshold == 0.02
trial
# Plot the removed variants. The course value is the large diamond.
plot_threshold_trials(trial, "Variants removed")
# Optional: add engine = "ggplot2" to plot_threshold_trials() to draw the plot with ggplot2 (install.packages("ggplot2") once first).
```


Plain PLINK 2 command for one trial. It writes only small files with the name that you give to `--out`, never a new dataset:

```sh
bin/plink2 --pfile results/guided/s3-8_state --geno 0.05 --make-just-pvar --out results/trials/s4-1_trial --threads 2 --memory 2048
```

The log file `results/trials/s4-1_trial.log` states how many variants were removed. To repeat the trial, change the number after `--geno` and use a new `--out` name.

The expected result of the trials:

| Threshold | Variants removed | Variants remaining |
| --- | --- | --- |
| 0.01 | 1,053 | 295,307 |
| **0.02 (course value)** | 801 | 295,559 |
| 0.05 | 561 | 295,799 |
| 0.1 | 0 | 296,360 |
| 0.2 | 0 | 296,360 |

How to read it. At 0.10 and 0.20 no variant is removed, because step 3.1 already removed the variants above 10% missing. From 0.05 to 0.01 the number of removed variants grows from 561 to 1,053. The course value of 0.02 removes 801.

Expected plot. For `--geno`, the horizontal axis shows the threshold and the vertical axis shows the number of variants removed. A red diamond marks the course value (0.02), where 801 variants are removed. The line joins the points in the order of the thresholds, so you can see how fast the count changes. The same plot with ggplot2 looks the same and has a light grid.

:::

## Step 4.2 · Differential missingness {#step-4-2}

We compare missing results in people with and without the disease to reduce false associations with disease. We remove variants with p-values below 1 × 10⁻⁵ (0.00001), which indicate differences that are very unlikely if missing results occur equally in both groups.

[Read step 4.2 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-4/step-4-2).

```{r}
#| label: s4-2
report <- guided_path(cfg, "4.2", "missing")  # <1>
run_plink(cfg, c("--pfile", guided_path(cfg, "4.1"), "--test-missing", "--out", report))
x <- guided_table(paste0(report, ".missing"))  # <2>
p <- as.numeric(x$P)
exclude <- guided_list(x$ID[!is.na(p) & p < 1e-5], guided_path(cfg, "4.2", "exclude.txt"))
run_plink(cfg, c("--pfile", guided_path(cfg, "4.1"), "--exclude", exclude, "--make-pgen", "--out", guided_path(cfg, "4.2")))  # <3>
# Course bookkeeping: records the counts for the next step. Do not change.
ops <- guided_replay_lists(cfg, "4.2", "4.1")
guided_register(cfg, "4.2", "4.1", 1844, 295439, operations = ops)
```

1. Compare missing results in people with and without the disease.
2. Read the test results and list variants with p-values below 0.00001.
3. Remove the listed variants and save the remaining data.

### What each option does

**Command 1: compare missing results**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM files named results/guided/s4-1_state. |
| `--test-missing` | Tests whether missing genotype calls differ between people with and without the disease. |
| `--out` | Starts the test report file names with results/guided/s4-2_missing. |

**Command 2: remove variants with unequal missing results**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM files named results/guided/s4-1_state. |
| `--exclude` | Removes variants listed in results/guided/s4-2_exclude.txt because their missingness test p-value is below 1 × 10⁻⁵ (0.00001). |
| `--make-pgen` | Saves the remaining data as PGEN, PVAR and PSAM files. |
| `--out` | Starts the output file names with results/guided/s4-2_state. |

Every command also uses `--threads 2` (PLINK runs at most two tasks at the same time) and `--memory 2048` (PLINK uses at most about 2 GB of memory).

::: {.callout-tip title="Expected result" collapse="true"}

120 variants are excluded. 295,439 variants and 1,844 samples remain.

:::

::: {.callout-note title="PLINK terminal equivalent"}

These commands are shown for reference. Run the R chunk above to follow the course.
R creates any lists needed between PLINK commands. On Windows, use `bin\plink2.exe`.

```sh
bin/plink2 --pfile results/guided/s4-1_state --test-missing --out results/guided/s4-2_missing --threads 2 --memory 2048
bin/plink2 --pfile results/guided/s4-1_state --exclude results/guided/s4-2_exclude.txt --make-pgen --out results/guided/s4-2_state --threads 2 --memory 2048
```

:::

## Step 4.3 · Allele frequency {#step-4-3}

We keep variants whose less common DNA version appears in at least 1% of the chromosome copies. This removes variants with too little information for the main disease analysis.

[Read step 4.3 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-4/step-4-3).

```{r}
#| label: s4-3
run_plink(cfg, c("--pfile", guided_path(cfg, "4.2"), "--maf", "0.01", "--make-pgen", "--out", guided_path(cfg, "4.3")))  # <1>
# Course bookkeeping: records the counts for the next step. Do not change.
ops <- guided_replay_lists(cfg, "4.3", "4.2")
guided_register(cfg, "4.3", "4.2", 1844, 239019, operations = ops)
```

1. Remove variants whose less common DNA version occurs in fewer than 1% of copies.

### What each option does

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM files named results/guided/s4-2_state. |
| `--maf` | Removes variants whose less common allele, or DNA version, appears in fewer than 1% of chromosome copies. |
| `--make-pgen` | Saves the remaining data as PGEN, PVAR and PSAM files. |
| `--out` | Starts the output file names with results/guided/s4-3_state. |

Every command also uses `--threads 2` (PLINK runs at most two tasks at the same time) and `--memory 2048` (PLINK uses at most about 2 GB of memory).

::: {.callout-tip title="Expected result" collapse="true"}

56,420 variants are removed because of their observed frequencies. 239,019 variants remain. The simulation did not plant a special list of rare artefacts (errors caused by the technology).

:::

::: {.callout-note title="PLINK terminal equivalent"}

These commands are shown for reference. Run the R chunk above to follow the course.
R creates any lists needed between PLINK commands. On Windows, use `bin\plink2.exe`.

```sh
bin/plink2 --pfile results/guided/s4-2_state --maf 0.01 --make-pgen --out results/guided/s4-3_state --threads 2 --memory 2048
```

:::

::: {.callout-tip title="Try other thresholds (optional)" collapse="true"}

This box is not part of the main path. No later step uses it. It does not change your results.

The minor allele frequency (MAF) is how often the less common version of a variant occurs. `--maf 0.01` removes variants with a MAF below 1%. A rare variant has few carriers, so its test has little power and gives unstable estimates. A higher limit removes more rare variants and keeps a cleaner set. A very high limit also removes real, common signals and shrinks the data a lot. Each trial starts from the cohort saved at 4.2 and changes the limit only.

```{r}
#| label: s4-3_thresholds
#| eval: false
# Optional. Each trial starts from the same input and changes one threshold only.
thresholds <- c(0.001, 0.005, 0.01, 0.02, 0.05)
trial <- threshold_counts(cfg, guided_path(cfg, "4.2"), "--maf", thresholds)
trial$course_value <- trial$threshold == 0.01
trial
# Plot the removed variants. The course value is the large diamond.
plot_threshold_trials(trial, "Variants removed")
# Optional: add engine = "ggplot2" to plot_threshold_trials() to draw the plot with ggplot2 (install.packages("ggplot2") once first).
```


Plain PLINK 2 command for one trial. It writes only small files with the name that you give to `--out`, never a new dataset:

```sh
bin/plink2 --pfile results/guided/s4-2_state --maf 0.02 --make-just-pvar --out results/trials/s4-3_trial --threads 2 --memory 2048
```

The log file `results/trials/s4-3_trial.log` states how many variants were removed. To repeat the trial, change the number after `--maf` and use a new `--out` name. PLINK 2 uses the founders to calculate the frequency when the sample table has family information. Our samples are all founders, so this makes no difference here.

The expected result of the trials:

| Threshold | Variants removed | Variants remaining |
| --- | --- | --- |
| 0.001 | 33,951 | 261,488 |
| 0.005 | 47,184 | 248,255 |
| **0.01 (course value)** | 56,420 | 239,019 |
| 0.02 | 89,204 | 206,235 |
| 0.05 | 156,235 | 139,204 |

How to read it. At 0.01 the course removes 56,420 variants. At 0.05 it would remove 156,235, which is more than half of the 295,439 variants that enter this step. Going from 0.01 to 0.001 keeps 22,469 more variants (the difference 56,420 minus 33,951). Many of them have only a handful of carriers.

Expected plot. For `--maf`, the horizontal axis shows the threshold and the vertical axis shows the number of variants removed. A red diamond marks the course value (0.01), where 56,420 variants are removed. The line joins the points in the order of the thresholds, so you can see how fast the count changes. The same plot with ggplot2 looks the same and has a light grid.

:::

## Step 4.4 · Hardy-Weinberg and sample size {#step-4-4}

We test whether DNA letter combinations on chromosomes 1 to 22 follow expected proportions in people without the disease. We remove variants that fail a rule based on the number of people tested, to reduce possible measurement errors.

[Read step 4.4 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-4/step-4-4).

```{r}
#| label: s4-4
psam <- guided_table(paste0(guided_path(cfg, "4.3"), ".psam"))  # <1>
controls <- guided_list(psam$IID[psam$Disease == "1"], guided_path(cfg, "4.4", "controls.txt"), TRUE)
report <- guided_path(cfg, "4.4", "hardy")  # <2>
run_plink(cfg, c("--pfile", guided_path(cfg, "4.3"), "--keep", controls, "--chr", "1-22", "--hardy", "midp", "--out", report))
hwe <- guided_table(paste0(report, ".hardy"))  # <3>
n_control <- as.numeric(hwe$HOM_A1_CT) + as.numeric(hwe$HET_A1_CT) + as.numeric(hwe$TWO_AX_CT)
cutoff <- 10^(-6 - 0.001 * pmax(0, n_control - 1000))
p <- as.numeric(hwe$MIDP)  # <4>
exclude <- guided_list(hwe$ID[!is.na(p) & p < cutoff], guided_path(cfg, "4.4", "exclude.txt"))
run_plink(cfg, c("--pfile", guided_path(cfg, "4.3"), "--exclude", exclude, "--make-pgen", "--out", guided_path(cfg, "4.4")))  # <5>
retained <- guided_table(paste0(guided_path(cfg, "4.4"), ".pvar"))$ID  # <6>
stopifnot(!any(c("rs4988235", "rs12913832", "rs1426654") %in% retained))
# Course bookkeeping: records the counts for the next step. Do not change.
ops <- guided_replay_lists(cfg, "4.4", "4.3")
guided_register(cfg, "4.4", "4.3", 1844, 238852, operations = ops)
```

1. Read the sample table and list people without the disease.
2. Test expected DNA letter combinations on chromosomes 1 to 22.
3. Calculate a cutoff for each variant from the number of people tested.
4. List variants with test p-values below their cutoff.
5. Remove the listed variants from all people and save the remaining data.
6. Check that the three named variants are absent from the saved data.

### What each option does

**Command 1: test expected DNA letter combinations**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM files named results/guided/s4-3_state. |
| `--keep` | Uses only people without the disease, listed in results/guided/s4-4_controls.txt, for this test. |
| `--chr` | Limits the test to chromosomes 1 to 22. |
| `--hardy` | Tests whether the shares of the three DNA letter combinations match those predicted from the allele frequencies when people mate at random. |
| &nbsp;&nbsp;&rarr; `midp` | Uses the mid-p version of the exact test, which adjusts for the limited possible outcomes of whole-number counts. |
| `--out` | Starts the test report file names with results/guided/s4-4_hardy. |

**Command 2: remove variants that fail the test**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM files named results/guided/s4-3_state, including people with and without the disease. |
| `--exclude` | Removes variants listed in results/guided/s4-4_exclude.txt after R applies the cutoff 10^(-6 - 0.001 * max(0, n_control - 1000)), where n_control counts people without the disease who have a result at that variant. |
| `--make-pgen` | Saves the remaining data as PGEN, PVAR and PSAM files. |
| `--out` | Starts the output file names with results/guided/s4-4_state. |

Every command also uses `--threads 2` (PLINK runs at most two tasks at the same time) and `--memory 2048` (PLINK uses at most about 2 GB of memory).

::: {.callout-tip title="Expected result" collapse="true"}

167 variants are excluded, and 238,852 remain. The strong planted errors are not the only failures. Eight unplanted variants and seven altered duplicate copies also fail. Some mild errors still pass. rs4988235, rs12913832 and rs1426654 leave here. They cannot be used as surviving markers in module 5.

:::

::: {.callout-note title="PLINK terminal equivalent"}

These commands are shown for reference. Run the R chunk above to follow the course.
R creates any lists needed between PLINK commands. On Windows, use `bin\plink2.exe`.

```sh
bin/plink2 --pfile results/guided/s4-3_state --keep results/guided/s4-4_controls.txt --chr 1-22 --hardy midp --out results/guided/s4-4_hardy --threads 2 --memory 2048
bin/plink2 --pfile results/guided/s4-3_state --exclude results/guided/s4-4_exclude.txt --make-pgen --out results/guided/s4-4_state --threads 2 --memory 2048
```

:::

::: {.callout-tip title="Try other thresholds (optional)" collapse="true"}

This box is not part of the main path. No later step uses it. It does not change your results.

The Hardy-Weinberg test gives a p-value for each variant in the controls. A smaller cutoff removes fewer variants. A larger cutoff removes more variants, including some that are only unusual. The course does not use one fixed cutoff. It uses the rule 10^(-6 - 0.001 * max(0, n_control - 1000)), where n_control is the number of controls tested at that variant. With 1,000 controls or fewer, the cutoff is 0.000001. Here there are 920 controls, so the course rule is the same as the fixed cutoff 1e-6. The trials below compare fixed cutoffs and the course rule.

```{r}
#| label: s4-4_thresholds
#| eval: false
# Optional. The trials use the table of tests that the step wrote. No PLINK run is needed.
cutoffs <- c(1e-3, 1e-4, 1e-6, 1e-8, 1e-10)
trial <- hwe_counts(guided_table(paste0(guided_path(cfg, "4.4", "hardy"), ".hardy")), cutoffs)
# The last row is the course rule. Its threshold is NA, so it is the course value.
trial$course_value <- is.na(trial$threshold)
trial
# Plot the removed variants for the fixed cutoffs. The course rule equals 1e-6 here.
plot_threshold_trials(trial, "Variants removed")
# Optional: add engine = "ggplot2" to plot_threshold_trials() to draw the plot with ggplot2 (install.packages("ggplot2") once first).
```


Plain PLINK 2 command for one trial. It writes only small files with the name that you give to `--out`, never a new dataset:

```sh
bin/plink2 --pfile results/guided/s4-3_state --keep results/guided/s4-4_controls.txt --chr 1-22 --hwe 1e-6 midp --make-just-pvar --out results/trials/s4-4_trial --threads 2 --memory 2048
```

The course does not use `--hwe`. It filters the table from `--hardy midp` in R, because its cutoff depends on the number of controls. The terminal command above uses a fixed cutoff. PLINK 2 can stop with an error when a cutoff is very strict for the sample size, unless you add a value `k` or the modifier `keep-fewhet` (read the `--hwe` entry of the PLINK 2 manual). PLINK 2 tests only founders by default.

The expected result of the trials:

| HWE p-value cutoff | Variants removed | Variants remaining |
| --- | --- | --- |
| 1e-3 | 700 | 238,319 |
| 1e-4 | 273 | 238,746 |
| 1e-6 | 167 | 238,852 |
| 1e-8 | 150 | 238,869 |
| 1e-10 | 127 | 238,892 |
| **course rule (course value)** | 167 | 238,852 |

How to read it. At 1e-3 the number removed is 700, and at 1e-4 it is 273. At 1e-6 it is 167, and at 1e-10 it is 127. The number falls slowly after 1e-6. The variants that fail even at 1e-10 show the strongest departures. The variants removed only at the looser cutoffs are less clear, and some of them may be sound.

Expected plot. For `HWE p-value cutoff`, the horizontal axis shows the threshold and the vertical axis shows the number of variants removed. A red diamond marks the course value (course rule), where 167 variants are removed. The line joins the points in the order of the thresholds, so you can see how fast the count changes. The same plot with ggplot2 looks the same and has a light grid.

:::

## Step 4.5 · Sex chromosomes, MT and duplicated sites {#step-4-5}

We remove variants on X, Y and mitochondrial DNA with unexpected results in more than 1% of people checked. We then rename variants by their DNA location and letters, keep one copy of matching duplicates and remove copies that disagree.

[Read step 4.5 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-4/step-4-5).

```{r}
#| label: s4-5
report <- guided_path(cfg, "4.5", "sexchr")  # <1>
run_plink(cfg, c("--pfile", guided_path(cfg, "4.4"), "--chr", "X,Y,MT", "--export", "A", "--out", report))
header <- strsplit(readLines(paste0(report, ".raw"), n = 1L), "[[:space:]]+")[[1]]  # <2>
raw <- read.table(paste0(report, ".raw"), header = TRUE, check.names = FALSE, quote = "", comment.char = "",
  colClasses = c(rep("character", 6), rep("integer", length(header) - 6L)), na.strings = "NA")
genotypes <- as.matrix(raw[, -(1:6), drop = FALSE]); genotypes[is.na(genotypes)] <- -1L  # <3>
ids <- sub("_[^_]+$", "", names(raw)[-(1:6)])
pvar <- guided_table(paste0(guided_path(cfg, "4.4"), ".pvar"))
chromosome <- pvar$CHROM[match(ids, pvar$ID)]
wrong <- numeric(length(ids))  # <4>
wrong[chromosome == "X"] <- colMeans(genotypes[raw$SEX == "1", chromosome == "X", drop = FALSE] == 1L)
wrong[chromosome == "Y"] <- colMeans(genotypes[raw$SEX == "2", chromosome == "Y", drop = FALSE] >= 0L)
wrong[chromosome == "MT"] <- colMeans(genotypes[, chromosome == "MT", drop = FALSE] == 1L)
exclude <- guided_list(ids[wrong > 0.01], guided_path(cfg, "4.5", "exclude.txt"))  # <5>
sex_state <- guided_path(cfg, "4.5", "sex_state")  # <6>
run_plink(cfg, c("--pfile", guided_path(cfg, "4.4"), "--exclude", exclude, "--make-pgen", "--out", sex_state))
stopifnot(all(guided_counts(sex_state) == c(1844, 238819)))
run_plink(cfg, c("--pfile", sex_state, "--set-all-var-ids", "@:#:$r:$a", "--rm-dup", "exclude-mismatch", "list",  # <7>
  "--make-pgen", "--out", guided_path(cfg, "4.5")))
# Course bookkeeping: records the counts for the next step. Do not change.
ops <- data.frame(option = c("--exclude", "--set-all-var-ids", "--rm-dup"), value = c(exclude, "@:#:$r:$a", "exclude-mismatch"))
guided_register(cfg, "4.5", "4.4", 1844, 238513, operations = ops)
rm(raw, genotypes); invisible(gc())  # <8>
```

1. Export X, Y and mitochondrial DNA results as a table.
2. Read the column names and the exported results.
3. Arrange the DNA results by person and variant and identify each chromosome.
4. Calculate the share of unexpected results for each variant.
5. List variants with unexpected results in more than 1% of people checked.
6. Remove the listed variants and check the remaining counts.
7. Rename variants by location and DNA letters and remove duplicate entries.
8. Free the computer memory used by the large tables.

### What each option does

**Command 1: export chromosome results for checking**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM files named results/guided/s4-4_state. |
| `--chr` | Selects only X, Y and MT, the mitochondrial chromosome. |
| `--export` | Writes genotype data in a text format for R to read. |
| &nbsp;&nbsp;&rarr; `A` | Writes a table with one row per person and values of 0, 1 or 2 for each variant. For chromosomes present in one copy, such as X in males, PLINK writes 0 or 2, so 2 does not mean two physical copies. |
| `--out` | Starts the export file names with results/guided/s4-5_sexchr. |

**Command 2: remove variants with unexpected chromosome results**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM files named results/guided/s4-4_state. |
| `--exclude` | Removes variants listed in results/guided/s4-5_exclude.txt because more than 1% of the people checked have unexpected results on X, Y or MT. |
| `--make-pgen` | Saves the remaining data as PGEN, PVAR and PSAM files. |
| `--out` | Starts the output file names with results/guided/s4-5_sex_state. |

**Command 3: rename variants and remove duplicate entries**

| Option or modifier | What it does |
| --- | --- |
| `--pfile` | Reads the PGEN, PVAR and PSAM files named results/guided/s4-5_sex_state. |
| `--set-all-var-ids` | Names each variant with @:#:$r:$a: chromosome, position, reference DNA version and alternative DNA version, separated by colons. |
| `--rm-dup` | Finds entries with the same variant name and keeps one copy when they match. |
| &nbsp;&nbsp;&rarr; `exclude-mismatch` | Removes all copies of a duplicated variant when their records disagree. |
| &nbsp;&nbsp;&rarr; `list` | Writes a list of the duplicated variant names. |
| `--make-pgen` | Saves the remaining data as PGEN, PVAR and PSAM files. |
| `--out` | Starts the output file names with results/guided/s4-5_state. |

Every command also uses `--threads 2` (PLINK runs at most two tasks at the same time) and `--memory 2048` (PLINK uses at most about 2 GB of memory).

::: {.callout-tip title="Expected result" collapse="true"}

33 variants with impossible calls on the sex chromosomes or MT are removed. The duplicate review removes 306 entries. It keeps one of each of the 280 matching pairs, and it removes both members of the 13 pairs that disagree. The final number of variants is 238,513.

:::

::: {.callout-note title="PLINK terminal equivalent"}

These commands are shown for reference. Run the R chunk above to follow the course.
R creates any lists needed between PLINK commands. On Windows, use `bin\plink2.exe`.

```sh
bin/plink2 --pfile results/guided/s4-4_state --chr X,Y,MT --export A --out results/guided/s4-5_sexchr --threads 2 --memory 2048
bin/plink2 --pfile results/guided/s4-4_state --exclude results/guided/s4-5_exclude.txt --make-pgen --out results/guided/s4-5_sex_state --threads 2 --memory 2048
bin/plink2 --pfile results/guided/s4-5_sex_state --set-all-var-ids '@:#:$r:$a' --rm-dup exclude-mismatch list --make-pgen --out results/guided/s4-5_state --threads 2 --memory 2048
```

:::

## Step 4.6 · Variant QC summary and checkpoint {#step-4-6}

We save a complete checked starting point for module 5. We check the saved files and counts so we can restart from the same data later.

[Read step 4.6 on the course website](https://www.manuelgentiluomo.it/teaching/gwas/module-4/step-4-6).

```{r}
#| label: s4-6
# Course bookkeeping: records the counts for the next step. Do not change.
guided_snapshot(cfg, "4.6", guided_path(cfg, "4.5"), 1844, 238513, parent = "4.5")  # <1>
check_step("4.6", data_dir = cfg$out, work_dir = cfg$out)
```

1. Save the complete dataset and check the saved files and counts.

### What each option does

No PLINK options are used in this step.

::: {.callout-tip title="Expected result" collapse="true"}

The full module 4 checkpoint has 1,844 samples and 238,513 variants. The counts and the SHA-256 checksums agree with the saved snapshot. A checksum is a short code that proves a file was not changed.

:::

::: {.callout-note title="PLINK terminal equivalent"}

No PLINK equivalent

:::

## Where next {#where-next}

- Previous: [Module 3: Sample quality control](module_03_sample_quality_control.qmd)
- Next: [Module 5: Population structure](module_05_population_structure.qmd)
- This module on the course website: [Module 4](https://www.manuelgentiluomo.it/teaching/gwas/module-4)
