---
title: "Multilevel Logistic Regression -- Polling"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r message=F}
setwd("/media/guerzhoy/Windows/STA303/lectures/lec10")
#setwd("c:/STA303/lectures/lec10")
library(lme4)
library(foreign)
```

Let's fit the model:

$$P(y_i) = logistic(\alpha^{state}_{j[i]}+\beta_{female}I_{female, i}+\beta_{black}I_{black, i})$$
$$\alpha^{state}_j\sim N(\mu_{\alpha}, \sigma^{2}_{state})$$



```{r}
polls <- read.dta ("polls.dta") #The 1988 Election: Bush (Rep.) vs Dukakis (Dem.)
fit <- glmer (bush ~ black + female + (1 | state), family=binomial(link="logit"), data=polls)
summary(fit)
ranef(fit)
```

It is better to include an interaction so that we can estimate the probability of voting Republican for each demographic, broken down by sex, race, and age (age is categorical as well).

We are now fitting the model

$$P(y_i) = logistic(\alpha^{state}_{j[i]}+\alpha^{age}_{k[i]}+\beta_{female}I_{female, i}+\beta_{black}I_{black, i})+\beta{female, black}I_{female, i}I_{black, i} $$
$$\alpha_j\sim N(\mu^{state}_{\alpha}, \sigma^{2}_{state})$$
$$\alpha_k\sim N(\mu^{age}_{\alpha}, \sigma^{2}_{state})$$


```{r}
polls$age <- factor(polls$age)
fit2 <- glmer (bush ~ black + female + black:female + (1 | state) + (1|age), family=binomial(link="logit"), data=polls)
summary(fit2)
ranef(fit2)

