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

{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE) library(dagitty) library(rethinking)

Week 5 - Elemental Confounds

Multiple regression is no oracle, but only a golem. It is logical, but the relationships it describes are conditional associations, not causal influences. Therefore additional information, from outside the model, is needed to make sense of it. This chapter presented introductory examples of some common frustrations: multicollinearity, post-treatment bias, and collider bias. Solutions to these frustrations can be organized under a coherent framework in which hypothetical causal relations among variables are analyzed to cope with confounding. In all cases, causal models exist outside the statistical model and can be difficult to test. However, it is possible to reach valid causal inferences in the absence of experiments. This is good news, because we often cannot perform experiments, both for practical and ethical reasons.

Place each answer inside the code chunk (grey box). The code chunks should contain a text response or a code that completes/answers the question or activity requested. Make sure to include plots if the question requests them.

Finally, upon completion, name your final output .html file as: YourName_ANLY505-Year-Semester.html and publish the assignment to your R Pubs account and submit the link to Canvas. Each question is worth 5 points.

Questions

5-1. In the divorce data, States with high numbers of members of the Church of Jesus Christ of Latter-day Saints (LDS) have much lower divorce rates than the regression models expected. Find a list of LDS population by State and use those numbers as a predictor variable, predicting divorce rate using marriage rate, median age at marriage, and percent LDS population (possibly standardized). You may want to consider transformations of the raw percent LDS variable. Make sure to include the ‘quap’ model, the ‘precis’ table and your explanation of the results.

```{r 5-1} data(WaffleDivorce) dataSet <- WaffleDivorce

#data

LDS_rate <- c(0.45, 4.23, 9.18, 5, 1.01, 8.02, 0.73, 0.20, 1.23, 0.90, 0.42, 7.28, 29.39, 0.54, 0.96, 0.17, 2.29, 0.49, 0.64, 0.81, 0.72, 0.39, 0.34, 0.58, 0.22, 5.10, 4.78, 1.29, 0.81, 0.37, 5.84, 0.71, 2.82, 4.58, 0.52, 1.2, 3.91, 0.4, 0.37, 0.83, 4.47, 0.75, 1.21, 67.97, 0.74, 1.13, 8.59, 0.92, 0.44, 13.5 )

ldsPopState <- quap( alist( Divorce ~ dnorm(mu,sigma), mu <- a + bXMarriage + bYMedianAgeMarriage + bZ*LDS_rate, a ~ dnorm(0,50), c(bX,bY,bZ) ~ dnorm(0,10), sigma ~ dunif(0,10) ), data=data)

precis(ldsPopState)


**5-2.** Sometimes, in order to avoid multicollinearity, people inspect pairwise correlations among
predictors before including them in a model. This is a bad procedure, because what matters is the
conditional association, not the association before the variables are included in the model. To highlight
this, consider the DAG X → Z → Y. Simulate data from this DAG so that the correlation
between X and Z is very large. Then include both in a model prediction Y. Do you observe any
multicollinearity? Why or why not? What is different from the legs example in the chapter?

```{r 5-2}
N <- 500
set.seed(1000)

r1 <- 0.95
r2 <- 0.35
x <- rnorm(N,10,2) 
z <- r1 * x + sqrt(1 - r1^2) * rnorm( N , 0 , 1)  
y <- r2 * z + sqrt(1 - r2^2) * rnorm( N , 0 , 1) 
data1 <- data.frame(x, y, z)
cor(data1)

mc <- quap( alist(
y ~ dnorm( mu , sigma ) ,
mu <- a + bl*x + br*z , 
a ~ dnorm( 0, 20 ) ,
bl ~ dnorm( 10 , 150 ) ,
br ~ dnorm( 10 , 150 ) ,
sigma ~ dexp( 1 )
), data=data1) 

precis(mc)

All three problems below are based on the same data. The data in data(foxes) are 116 foxes from 30 different urban groups in England. These foxes are like street gangs. Group size varies from 2 to 8 individuals. Each group maintains its own urban territory. Some territories are larger than others. The area variable encodes this information. Some territories also have more avgfood than others. We want to model the weight of each fox. For the problems below, assume the following DAG:

```{r echo=FALSE} quest <- dagitty( “dag {area -> avgfood avgfood -> groupsize avgfood -> weight groupsize -> weight }”)

coordinates (quest) <- list(x=c(area=1,avgfood=0,groupsize=2, weight=1), y=c(area=0, avgfood=1, groupsize=1, weight=2))

drawdag(quest, lwd = 2)


**5-3.** Use a model to infer the total causal influence of area on weight. Would increasing the area
available to each fox make it heavier (healthier)? You might want to standardize the variables. Regardless,
use prior predictive simulation to show that your model’s prior predictions stay within the
possible outcome range.

```{r 5-3}
data(foxes)
dataSet2 <- foxes
dataSet2$area = scale( dataSet2$area )
dataSet2$food = scale( dataSet2$avgfood )
dataSet2$groupsize = scale( dataSet2$groupsize )
dataSet2$weight = scale( dataSet2$weight)

causalInfluence = quap(
    alist(
        weight ~ dnorm( mu , sigma ) ,
        mu <- a + bA*area ,
        a ~ dnorm( 0 , 0.4 ) ,
        bA ~ dnorm( 0 , 0.7 ) ,
        sigma ~ dexp( 1 )
) , data=dataSet2 )

precis(causalInfluence)

library(dplyr)
library(tibble)
library(tidyr)
causalInfluence %>% 
  extract.prior() %>% 
  link(causalInfluence, post = .,
    data = list(area = seq(-2, 2, length.out = 20))) %>% 
  as_tibble() %>%
  pivot_longer(cols = everything(), values_to = "weight") %>%
  add_column(
    area = rep(seq(-2, 2, length.out = 20), 1000),
    type = rep(as.character(1:1000), each = 20)) %>% 
  ggplot() +
  geom_line(aes(x = area, y = weight, group = type), 
            alpha = 0.1, colour = "red") +
  labs(x = "Area (standard)", y = "Weight (standard)", 
       caption = "Simulation.") +
  theme_minimal()

5-4. Now infer the causal impact of adding food to a territory. Would this make foxes heavier? Which covariates do you need to adjust for to estimate the total causal influence of food?

```{r 5-4} causalImpactFood <- quap(alist(weight ~ dnorm(mu, sigma),
mu <- a + BF*avgfood, a ~ dnorm(0, 0.2), BF ~ dnorm(0, 0.5), sigma ~ dexp(1)),data=dataSet2)

precis(causalImpactFood)


**5-5.** Now infer the causal impact of group size. Which covariates do you need to adjust for? Looking
at the posterior distribution of the resulting model, what do you think explains these data? That is,
can you explain the estimates for all three problems? How do they go together?

```{r 5-5}
causalImpactGrpSize <- quap(alist(weight ~ dnorm(mu, sigma),  
                  mu <- a + BF*avgfood + BG*groupsize, 
                  a ~ dnorm(0, 0.2), 
                  c(BF, BG) ~ dnorm(0, 0.5), 
                  sigma ~ dexp(1)),data=dataSet2) 

precis(causalImpactGrpSize)