---
title: "Lab-Confidence-Intervals"
author: "J. Lucas McKay"
date: "2023-03-02"
output: html_document
---

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

# Population Mean CI

```{r}
library(tidyverse)

tremor = read_csv("https://jlucasmckay.bmi.emory.edu/global/bmi510/Labs/tremor-hz.csv") |> 
  filter(tremor == "present")

tremor |> ggplot(aes(hz_med)) + geom_histogram(bins=40)

# sample mean value
mn = mean(tremor$hz_med)

# parametric confidence interval for sample mean
ci = function(d,alpha=0.05){
  n = length(d)
  mu = mean(d)
  s = sd(d)
  sem = s/sqrt(n)
  tcrit = qt(1-(alpha/2),df=n-1)
  interval = tcrit*sem
  ci.out = mu + interval*c(-1,1)
  names(ci.out) = scales::percent(c(alpha/2,1-alpha/2),0.1)
  ci.out
}

ci(tremor$hz_med)

# bootstrapped confidence interval for sample mean
bootci = function(d,n_rep=10000,alpha=0.05){
  n = length(d)
  means = replicate(n_rep,mean(sample(d,n,replace=T))) |> sort()
  quantile(means,c(alpha/2,1-alpha/2))
}

bootci(tremor$hz_med)

# we haven't done a lot of models yet, but here is one simple one.
m1 = lm(hz_med~1,tremor)
m1 |> names()
m1 |> confint()
# compare the the first parametric case





```

# Population Proportion CI, Wald Approximation

$$
\hat{p}\pm z_{\alpha/2}\sqrt{\hat{p}(1-\hat{p})/n}
$$

```{r}
alpha = 0.05
n.successes = 5
n.trials = 20
p.hat = n.successes/n.trials
z.crit = abs(qnorm(alpha/2))
err = sqrt(p.hat*(1-p.hat)/n.trials)
wald.ci = c(p.hat - z.crit*err,p.hat + z.crit*err)
names(wald.ci) = scales::percent(c(alpha/2,1-alpha/2),0.1)

wald.ci


# try with 2 successes

```

# Population Proportion CI, Add 4

```{r}
PropCIs::add4ci
PropCIs::add4ci(2,20,0.95)
```

