---
title: "FW 536 — Day 2 afternoon lab (Linear models & GLMs) — Your Name"
author: "Your Name Here"
date: "`r Sys.Date()`"
output:
  html_document:
    self_contained: true
    toc: true
    toc_depth: 3
    toc_float: true
    code_folding: show
    theme: cosmo
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
```

# Day 2 afternoon lab — Linear models & GLMs problem set

This template matches the **afternoon** section (Problems 5–12) of
[`problem_set.html`](problem_set.html). Read each problem statement there,
write your work below, **Knit** to HTML, and upload the `.html` to the
matching Canvas assignment.

Several problems load real datasets from this Day's `data/` folder:

- `data/sockeye_adult.csv` — daily sockeye counts and flow-corrected qPCR eDNA
  (Levi et al. 2019); used in **Problem 5**.
- `data/titanic_long.csv` — one row per passenger; used in **Problems 6 and 7**.
- `data/titanic_prop.csv` — aggregated (Yes, No) survival counts; used in **Problem 6**.

Keep the `.Rmd` in this folder so the `read.csv("data/...")` paths resolve.
For setup help see the [R Markdown tutorial](../rmarkdown_tutorial.html).

---

# Setup

```{r}
# Load the packages you'll need. Add or remove as appropriate.
library(ggplot2)
library(dplyr)
library(MASS)        # for glm.nb
library(effects)     # for allEffects() plots
library(emmeans)     # for pairwise contrasts on the fitted GLM
```

---

# Problem 5 — Sockeye eDNA → daily count: pick the right model

> Load `data/sockeye_adult.csv`, subset to `Sockeye_Adults`, build a `Year`
> factor, and keep complete cases. Fit `lm(log(Count+1) ~ ...)`, Poisson,
> quasipoisson, and `glm.nb`. Diagnose overdispersion; compare SEs on the
> eDNA slope; back-transform the log-link slope to a "doubling of eDNA →
> ×__ count" statement.

**My work:**

```{r}
sock <- read.csv("data/sockeye_adult.csv", stringsAsFactors = FALSE)
sock <- subset(sock, Sockeyetype == "Sockeye_Adults")
sock$Year <- factor(sub(".*/", "", sock$Date))            # "15" or "16"
sock <- sock[!is.na(sock$Count) & !is.na(sock$Qcorr_qPCR), ]
min_pos <- min(sock$Qcorr_qPCR[sock$Qcorr_qPCR > 0])
sock$logED <- log(sock$Qcorr_qPCR + min_pos)

# Fit the four models and compare deviance/df, dispersion, and SE(logED) here
```

**Answer / biological interpretation:**


---

# Problem 6 — Titanic survival: individual-level vs aggregated binomial

> Fit `glm(survived ~ class, binomial, long)` and
> `glm(cbind(Yes, No) ~ Class, binomial, prop)`. Show the fitted class
> probabilities match the raw proportions; explain the reference-level
> difference between the two coefficient tables; convert log-odds → odds →
> probability by hand; give an odds-ratio sentence.

**My work:**

```{r}
long <- read.csv("data/titanic_long.csv", stringsAsFactors = TRUE)
prop <- read.csv("data/titanic_prop.csv", stringsAsFactors = TRUE)

# Fit both models; verify fitted probabilities against raw proportions here
```

**Answer / biological interpretation:**


---

# Problem 7 — Titanic: does the class effect depend on sex?

> Fit `glm(survived ~ class * sex + age, binomial, long)`. Use
> `allEffects()` and `emmeans(fit, pairwise ~ class | sex, type="response")`.
> Report the largest within-sex class odds ratio, the child odds ratio, the
> female first-vs-third probability difference, and why `emmeans` (not
> `TukeyHSD`) is the right tool.

**My work:**

```{r}
long <- read.csv("data/titanic_long.csv", stringsAsFactors = TRUE)

# fit <- glm(survived ~ class * sex + age, family = binomial, data = long)
# plot(allEffects(fit))
# emmeans(fit, pairwise ~ class | sex, type = "response")
```

**Answer / biological interpretation:**


---

# Problem 8 — Reading a Poisson coefficient table as biology

> Given intercept $+0.10$, oak-canopy slope $+0.020$/percent, elevation slope
> $-0.55$/km: intercept back-transform; multiplicative effect of 10→60% oak;
> elevation half-decay; one manuscript sentence.

**My work:**

```{r}
# Your R code here
```

**Answer / biological interpretation:**


---

# Problem 9 — When the sign of an effect flips between groups

> Poisson interaction `macros ~ discharge * season`: intercept 3.50,
> discharge $-0.30$, seasonFall $+0.40$, discharge:seasonFall $+0.50$.
> Seasonal slopes as multiplicative effects; fall intercept back-transform;
> crossover discharge; why the interaction matters.

**My work:**

```{r}
# Your R code here
```

**Answer / biological interpretation:**


---

# Problem 10 — Turning counts into rates with an offset

> Longline bycatch with `offset(log(hooks))`. What the offset intercept
> means; why the offset is on the log scale; per-hook rate sentence for a
> depth slope of $+0.012$/m; direction of Analyst A's bias.

**My work:**

```{r}
# Your R code here
```

**Answer / biological interpretation:**


---

# Problem 11 — Occupancy thresholds and choosing a management lever

> Logistic `present ~ basal_area + shrub_cover`: intercept $-3.0$, BA $+0.08$,
> shrub $+0.04$. Threshold BA at 25% and 50% shrub; marginal effect at
> $p = 0.5$ (and divide-by-4 check); which of two interventions gives the
> larger gain at $p = 0.3$.

**My work:**

```{r}
# Your R code here
```

**Answer / biological interpretation:**


---

# Problem 12 — From a log-scale contrast to a percent change with uncertainty

> Gamma-log contrast $\hat\beta = -0.65$, 95% CI $(-0.95, -0.35)$.
> Back-transform point estimate and CI; is the multiplicative CI symmetric?;
> percent-decrease statement; why exponentiate endpoints, not the midpoint.

**My work:**

```{r}
# Your R code here
```

**Answer / biological interpretation:**


---

# (Optional) Embed a photo of hand-written work

For problems easier to do on paper, photograph and embed:

```{r, echo=FALSE, eval=FALSE, out.width="60%", fig.cap="Hand-derivation for Problem N"}
knitr::include_graphics("images/problemN_derivation.jpg")
```

(Change `eval=FALSE` to `eval=TRUE` after saving an image. See the
[R Markdown tutorial](../rmarkdown_tutorial.html) for details.)

---

# Submission checklist

- [ ] Answered every afternoon problem (5–12) from `problem_set.html`.
- [ ] Loaded `data/sockeye_adult.csv` (Problem 5) and `data/titanic_long.csv` / `data/titanic_prop.csv` (Problems 6–7); `.Rmd` kept in this folder so paths resolve.
- [ ] Exponentiated every log/logit coefficient and stated the effect as a multiplicative factor, odds ratio, or probability change.
- [ ] Knitted to HTML without errors.
- [ ] Photos (if any) embedded with `self_contained: true` in the YAML.
- [ ] Uploaded the `.html` to the matching Canvas assignment.
