---
title: "R_markdown_depression_example"
author: "Carolyn J. Anderson"
date: "4/19/2022"
output: 
    html_document:
      toc: yes
---
The R in this document reproduces the results in the lecture on multilevel logistic regression.  The data are from Agresti (2002) who got is from Koch et al. (1977)

# Setup

The package that we'll use

```{r setup, message=FALSE, warning=FALSE,include=TRUE}
library(lme4)
library(lmerTest)
library(gee)    # for generalized estimating equations
library(MASS)   # For confidence limits for parameters
```

Read in the data and examine

```{r data}
depress <- read.table(file="D:/Dropbox/edps587/lectures/10 logreg/depression_data_long.txt", header=TRUE)

head(depress)
```

Note that there are 3 observations per subject, one for each time point.  

# Ignore heirarchical structure

The very nieve approach to logistic regression for clustered data is below

```{r logreg}
# standard logistic regression

model1a <- glm(y ~ severe +  Rx + time + Rx*time, data=depress, family=binomial)
summary(model1a)
```

The z's statistics for coefficients are sqrt(Wald).


#  GEE using exchangable

```{r gee}
model.gee <- gee(y ~ severe  + Rx + time + Rx*time, id, data=depress, family=binomial, corstr="exchangeable")
summary(model.gee)
```

#  Random Effects

## Laplace (default)

```{r laplace}
model2 <- glmer(y ~ severe +  Rx + time + Rx*time + (1 |id ), data=depress, family=binomial)
summary(model2)
```

## Guass Quadrature

```{r agq}
model3 <- glmer(y ~ severe +  Rx + time + Rx*time + (1 |id ), data=depress, family=binomial, nAGQ=10)
summary(model3)
```

# Extract R script

```{r extractR, eval=FALSE}
setwd("D:/Dropbox/edps587/lectures/10 logreg")
knitr::purl("R_markdown_depression_example.Rmd","R_script_depression_example.txt")

