---
title: "Logistic Regression for Binomial Counts"
output: html_document
---

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

## Logistic Regression for Binomial Counts
Read in the data
```{r message=F}
require(Sleuth3)
krunnit <- case2101
```

Let's plot the logits of the proportions vs. the logits of the probability of going extinct.

```{r message=FALSE}
require(gtools)
require(ggplot2)
krunnit$pi_hat <- krunnit$Extinct/krunnit$AtRisk
qplot(Area, logit(pi_hat), data=krunnit)
```

Doesn't look great. What about the log(Area) vs. the logits?

```{r}
qplot(log(Area), logit(pi_hat), data=krunnit)
```

Better!


Let's fit the model

```{r}
fit <- glm(cbind(Extinct, AtRisk-Extinct)~log(Area), family=binomial(), data=krunnit)
summary(fit)
```


Note that we can interpret this as plain old logistic regression:
```{r}
data <- data.frame(Island=c(), Area=c(), Died=c())
for(i in 1:dim(krunnit)[1]){
  new_data <- data.frame(Island=rep(krunnit[i, "Island"], krunnit[i, "AtRisk"]), 
                         Area= rep(krunnit[i, "Area"], krunnit[i, "AtRisk"]),
                         Died=c(rep(1, krunnit[i, "Extinct"]), rep(0, krunnit[i, "AtRisk"]-krunnit[i, "Extinct"])))
  data <- rbind(data, new_data)
}

fit_logistic <- glm(Died~log(Area), family=binomial(), data=data)
summary(fit_logistic)
```
(Run the R code to view the new data we created.)


If you double the area, how to the odds change?
```{r}
new_dat <- data.frame(Island=c("small", "large"), Area=c(100, 200))
predict(fit, new_dat)
plogis(predict(fit, new_dat))
0.059/0.071
2^-0.3
```

We can also get the "CI" for the prediction:
```{r}
2^data.frame(confint(fit))["log(Area)",]
```



```{r}
pi <- sum(krunnit$Extinct)/sum(krunnit$AtRisk)
pi
fit0          <- glm(cbind(Extinct, AtRisk-Extinct)~1, family=binomial(), data=krunnit)
summary(fit0)
plogis(-1.5794)  #probability of extinction, regardless of islad

fit_saturated <- glm(cbind(Extinct, AtRisk-Extinct)~Island, family=binomial(), data=krunnit)
summary(fit)
summary(fit_saturated)
anova(fit, fit_saturated, test="LRT")
```

