---
title: "Accounting for Weights in the Model"
author: "Simon Bonner"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Weighted Regression}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

In some cases the response variable may be an average of responses from within the same subject or group. In this case, the variances for two observations having the same covariates will not be identical if the size of the groups vary. Instead, it will be inversely proportional to the size of the group. Mathematically, if the observed response is the group average $\bar{Y}_i=\sum_{j=1}^n_i Y_{ij}/n_i$ and $Y_{ij} \sim N(\mu_i,\sigma^2_i)$ where $\sigma^2_i$ may vary by group and depend on covariates then
$$\bar{Y}_i \sim N(\mu_i,\sigma^2_i/n_i).$$
This situation can be accommodated in `dalmatian` by specifying a column of weights within the data frame that provides the group size. Here is an example with simulated data that demonstrates this feature and shows the importance of properly accounting for weights. 

# Simulated data
Data for this example are contained in the data frame `weights.df` saved within the file `weights-data-1.RData`. The data were generated from the model
$$Y_{ij} \sim N(x_i,\exp(1+x_i)^2)$$
with $i=1,\ldots,100$ indexing the groups and $j$ the observarions within groups. In the data, the number of observations per group ranges from 5 to 43. 

```{r}
## Load library
library(dalmatian)

## Load simulated data
data(weights_1_simulate)
head(weights.df)
```
The three columns in the data frame record the number of responses per group (`n`), the value of the covariate (`x`), and the mean response (`y`).

# Model 1: No Weights

First we run the model with no weights. 

```{r}
## Mean model
mymean=list(fixed=list(name="alpha",formula=~ x,
            priors=list(c("dnorm",0,.001))))

## Variance model
myvar=list(fixed=list(name="psi",link="log",formula=~ x,
           priors=list(c("dnorm",0,.001))))

## Set working directory
## By default uses a system temp directory. You probably want to change this.
workingDir <- tempdir()

## Define list of arguments for jags.model()
jm.args = list(file="weights_1_jags.R",n.adapt=1000)

## Define list of arguments for coda.samples()
cs.args = list(n.iter=1000)

## Run the model using dalmatian
results1 <- dalmatian(
  df = weights.df,
  mean.model = mymean,
  variance.model = myvar,
  jags.model.args = jm.args,
  coda.samples.args = cs.args,
  response = "y",
  overwrite = TRUE,
  debug = FALSE
)

## Numerical summary statistics
summary(results1)

## Graphical summaries
caterpillar1 <- caterpillar(results1)
```

From the summaries we can see that that the intercept in the variance model is being underestimated. The true value is 1, but the posterior mean is -.24 with 95% HPD interval (-.39,-.12). 

# Model 2: Weights

We now re-run the model including the weights.

```{r}
## Specify column containing weights
myvar$weights = "n"

## Run model
jm.args = list(file="weights_2_jags.R",n.adapt=1000)

results2 = dalmatian(df=weights.df,
                        mean.model=mymean,
                        variance.model=myvar,
                        jags.model.args=jm.args,
                        coda.samples.args=cs.args,
                        response="y",
                     overwrite = TRUE,
                        debug=FALSE)

## Numerical summary statistics
summary(results2)

## Graphical summaries
caterpillar2 <- caterpillar(results2)

```

The new output shows that the estimate of the intercept for the variance model, .95, is now very close to the truth and the 95% credible interval, (.82,1.10) easily covers the true value of 1.  
