Exercise in R: extensions to Mendel

Goal

By the end of this exercise you should be able to:

  • in R, apply one function to a whole list of hypotheses with purrr::map_dbl() or sapply(), and collect the results in a tibble.

Before you start

This page builds on the by-hand part of the Exercise, so do that first. You need the packages readr, dplyr, purrr, tidyr and ggplot2. Download labrador_f2.csv and save it in a data/ folder of your R project.

Tasks

New idiom today: apply one function to every element of a list. You write a function once, put the hypotheses in a named list, and let purrr::map_dbl() (or base R sapply()) call the function for each hypothesis. map_dbl(xs, f) returns a numeric vector, one value per element of xs, named like xs. Inside map_dbl() you can write a short function as \(h) ..., where h is one element of the list.

The data. data/labrador_f2.csv has coat colours of 384 Labrador pups from matings between black BbEe parents. This is an invented teaching dataset, shaped like pooled kennel records. The recorder split the yellow pups into “fox red” and “cream”, because she wondered if the shade was a third Mendelian class. (In real yellow Labradors the shade varies a lot and is not explained by B or E: this is variable expressivity.)

R1. Load the data and look at it. Add a column with each count expressed in 16ths. Which ratio do the 16ths suggest?

library(readr)
library(dplyr)
library(purrr)
library(tidyr)
library(ggplot2)

f2 <- read_csv("data/labrador_f2.csv", show_col_types = FALSE)
f2
f2 |> mutate(sixteenths = round(16 * count / sum(count), 2))

R2. Write two functions: chisq_stat(obs, ratio), which returns the χ² statistic for observed counts obs and a ratio such as c(9, 3, 4), and chisq_p(obs, ratio), which returns the p-value with df = number of classes − 1 (use pchisq() with lower.tail = FALSE). Check chisq_p(obs, c(9, 3, 3, 1)) against chisq.test().

obs <- setNames(f2$count, f2$coat)   # a named vector: black, chocolate, fox red, cream

chisq_stat <- function(obs, ratio) {
  expected <- sum(obs) * ratio / sum(ratio)
  # ... return the chi-square statistic
}
chisq_p <- function(obs, ratio) {
  # ... use chisq_stat() and pchisq()
}

R3. Each hypothesis says which recorded classes belong together and what the ratio is. group gives, for each of the four recorded classes (black, chocolate, fox red, cream), the number of the class it belongs to under that hypothesis. tapply() adds up the counts within each group. Use map_dbl() to compute χ² and p for every hypothesis, and collect them in a tibble sorted by p. Then get the same p-values with sapply().

collapse <- function(obs, group) tapply(obs, group, sum)

hypotheses <- list(
  "9:3:3:1" = list(group = c(1, 2, 3, 4), ratio = c(9, 3, 3, 1)),
  "9:3:4"   = list(group = c(1, 2, 3, 3), ratio = c(9, 3, 4)),
  "9:7"     = list(group = c(1, 2, 2, 2), ratio = c(9, 7)),
  "12:3:1"  = list(group = c(1, 1, 2, 3), ratio = c(12, 3, 1)),
  "15:1"    = list(group = c(1, 1, 1, 2), ratio = c(15, 1))
)
collapse(obs, hypotheses[["9:3:4"]]$group)   # black, chocolate, all yellow

results <- tibble(
  hypothesis = names(hypotheses),
  df    = map_int(hypotheses, \(h) length(h$ratio) - 1L),
  chisq = map_dbl(hypotheses, \(h) chisq_stat(collapse(obs, h$group), h$ratio)),
  p     = map_dbl(hypotheses, \(h) chisq_p(collapse(obs, h$group), h$ratio))
) |>
  arrange(desc(p))
results

Which hypotheses are rejected at α = 0.05? Two hypotheses fit. Which one would you choose, and why?

R4. Make a tibble of observed and expected counts for the best-fitting ratio, 9 : 3 : 4 (black, chocolate, yellow), and plot them side by side with pivot_longer() and geom_col(position = "dodge").

R5. (yellow mice) Yellow × yellow mice gave 118 yellow and 62 agouti pups (invented counts). Put the two hypotheses 2:1 and 3:1 in a named list and use your chisq_stat() and chisq_p() with map_dbl() to test both. Which fits? What does that tell you about AYAY?

Solutions

R1. The 16ths are about 8.8 : 3.2 : 2.2 : 1.9. Black and chocolate look like 9 and 3, but fox red and cream are close to 2 and 2, not 3 and 1. Together they make 4.0, which suggests 9 : 3 : 4.

f2
# A tibble: 4 × 2
  coat      count
  <chr>     <dbl>
1 black       211
2 chocolate    76
3 fox red      52
4 cream        45
f2 |> mutate(sixteenths = round(16 * count / sum(count), 2))
# A tibble: 4 × 3
  coat      count sixteenths
  <chr>     <dbl>      <dbl>
1 black       211       8.79
2 chocolate    76       3.17
3 fox red      52       2.17
4 cream        45       1.88

R2.

chisq_stat <- function(obs, ratio) {
  expected <- sum(obs) * ratio / sum(ratio)
  sum((obs - expected)^2 / expected)
}
chisq_p <- function(obs, ratio) {
  pchisq(chisq_stat(obs, ratio), df = length(obs) - 1, lower.tail = FALSE)
}
obs <- setNames(f2$count, f2$coat)
chisq_p(obs, c(9, 3, 3, 1))
[1] 2.195437e-05
chisq.test(obs, p = c(9, 3, 3, 1) / 16)

    Chi-squared test for given probabilities

data:  obs
X-squared = 24.269, df = 3, p-value = 2.195e-05

The same p-value. 9 : 3 : 3 : 1 is rejected: the split of yellow into fox red and cream is not 3 : 1.

R3.

collapse(obs, hypotheses[["9:3:4"]]$group)
  1   2   3
211  76  97
results
# A tibble: 5 × 4
  hypothesis    df  chisq          p
  <chr>      <int>  <dbl>      <dbl>
1 9:3:4          2  0.348 0.840
2 9:7            1  0.265 0.607
3 9:3:3:1        3 24.3   0.0000220
4 15:1           1 19.6   0.00000955
5 12:3:1         2 23.9   0.00000635
sapply(hypotheses, \(h) chisq_p(collapse(obs, h$group), h$ratio))
     9:3:3:1        9:3:4          9:7       12:3:1         15:1
2.195437e-05 8.401374e-01 6.070112e-01 6.350266e-06 9.546920e-06

9 : 3 : 3 : 1, 12 : 3 : 1 and 15 : 1 are rejected (p < 0.001). 9 : 3 : 4 and 9 : 7 both fit. Choose 9 : 3 : 4. The 9 : 7 model is just 9 : 3 : 4 with chocolate and yellow merged, so it fits whenever 9 : 3 : 4 fits; but chocolate and yellow pups clearly look different, and 9 : 7 cannot explain that. A model has to explain every class you can tell apart. Do not pick a model just because its p-value is highest; here the two p-values are for tests with different df and different data groupings. The fox red / cream split is not a Mendelian class: it is variation in the shade of yellow (expressivity).

R4.

best <- hypotheses[["9:3:4"]]
fit <- tibble(
  phenotype = c("black", "chocolate", "yellow"),
  observed  = as.vector(collapse(obs, best$group)),
  expected  = sum(obs) * best$ratio / sum(best$ratio)
)
fit
# A tibble: 3 × 3
  phenotype observed expected
  <chr>        <dbl>    <dbl>
1 black          211      216
2 chocolate       76       72
3 yellow          97       96
fit |>
  pivot_longer(c(observed, expected), names_to = "type", values_to = "count") |>
  ggplot(aes(phenotype, count, fill = type)) +
  geom_col(position = "dodge") +
  labs(x = "coat colour", y = "number of pups",
       title = "Labrador F2: observed vs expected under 9:3:4")

The bars for observed and expected are almost the same height in every class: 211 vs 216, 76 vs 72, 97 vs 96.

R5.

mice <- c(yellow = 118, agouti = 62)
mouse_hyp <- list("2:1" = c(2, 1), "3:1" = c(3, 1))
tibble(
  hypothesis = names(mouse_hyp),
  chisq = map_dbl(mouse_hyp, \(r) chisq_stat(mice, r)),
  p     = map_dbl(mouse_hyp, \(r) chisq_p(mice, r))
)
# A tibble: 2 × 3
  hypothesis chisq       p
  <chr>      <dbl>   <dbl>
1 2:1         0.1  0.752
2 3:1         8.56 0.00343

2 : 1 fits (expected 120 : 60, χ² = 0.1) and 3 : 1 is rejected (expected 135 : 45, χ² = 8.56, p = 0.003). So the AYAY class (1/4 of zygotes) is missing among the live pups: AY is a recessive lethal.

Where this leads

In Pedigree analysis you write a risk function that works on a whole vector of carrier frequencies at once, and simulate families with replicate().