Chapter 8 - Conditional Manatees

This chapter introduced interactions, which allow for the association between a predictor and an outcome to depend upon the value of another predictor. While you can’t see them in a DAG, interactions can be important for making accurate inferences. Interactions can be difficult to interpret, and so the chapter also introduced triptych plots that help in visualizing the effect of an interaction. No new coding skills were introduced, but the statistical models considered were among the most complicated so far in the book.

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. Problems are labeled Easy (E), Medium (M), and Hard(H).

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

8E1. For each of the causal relationships below, name a hypothetical third variable that would lead to an interaction effect:

  1. Bread dough rises because of yeast.
  2. Education leads to higher income.
  3. Gasoline makes a car go.
# 1. Bread dough rises because of yeast. water may affect the result
# 2. Education leads to higher income. Degree level may affect the income
# 3. Gasoline makes a car go. Wheels helps a car move

8E2. Which of the following explanations invokes an interaction?

  1. Caramelizing onions requires cooking over low heat and making sure the onions do not dry out.
  2. A car will go faster when it has more cylinders or when it has a better fuel injector.
  3. Most people acquire their political beliefs from their parents, unless they get them instead from their friends.
  4. Intelligent animal species tend to be either highly social or have manipulative appendages (hands, tentacles, etc.).
# 1. Caramelizing onions requires cooking over low heat and making sure the onions do not dry out. This invokes an interaction as effect of heat depends on the moisture in onions 

8E3. For each of the explanations in 8E2, write a linear model that expresses the stated relationship.

#1 caramelizing ~ heat + dryness + heat*dryness
#2 max_speed ~ n_cylinders + fuel_injector
#3 political_beliefs ~ parents_beliefs*(1-has_political_friends) + has_political_friends*friends_beliefs
#4 intelligence ~ social_level + has_manipulalative_appendages 

8M1. Recall the tulips example from the chapter. Suppose another set of treatments adjusted the temperature in the greenhouse over two levels: cold and hot. The data in the chapter were collected at the cold temperature. You find none of the plants grown under the hot temperature developed any blooms at all, regardless of the water and shade levels. Can you explain this result in terms of interactions between water, shade, and temperature?

# Temperature is the main factor, shade and water depends on it. 
# There is an interaction between Temperature and Water, Temperature and Shade, Temperature and Water and Shade

8M2. Can you invent a regression equation that would make the bloom size zero, whenever the temperature is hot?

# bloom ~ is_temp_cold * (a + bW*w + bS*s + bWS*w*s)

8M4. Repeat the tulips analysis, but this time use priors that constrain the effect of water to be positive and the effect of shade to be negative. Use prior predictive simulation. What do these prior assumptions mean for the interaction prior, if anything? Visualize the prior simulation.

data(tulips)
d <- tulips
str(d)
## 'data.frame':    27 obs. of  4 variables:
##  $ bed   : Factor w/ 3 levels "a","b","c": 1 1 1 1 1 1 1 1 1 2 ...
##  $ water : int  1 1 1 2 2 2 3 3 3 1 ...
##  $ shade : int  1 2 3 1 2 3 1 2 3 1 ...
##  $ blooms: num  0 0 111 183.5 59.2 ...
d$blooms_std <- d$blooms / max(d$blooms)
d$water_cent <- d$water - mean(d$water)
d$shade_cent <- d$shade - mean(d$shade)

a <- rnorm( 1e4 , 0.5 , 1 ) 
sum( a < 0 | a > 1 ) / length( a )
## [1] 0.6162
a <- rnorm( 1e4 , 0.5 , 0.25 ) 
sum( a < 0 | a > 1 ) / length( a )
## [1] 0.0474
m8.6 <- quap( 
alist(
blooms_std ~ dnorm( mu , sigma ) ,
mu <- a + bw*water_cent + bs*shade_cent ,
a ~ dnorm( 0.5 , 0.25 ) ,
bw ~ dnorm( 0 , 0.25 ) ,
bs ~ dnorm( 0 , 0.25 ) ,
sigma ~ dexp( 1 )
) ,
data=d )

m8.7 <- quap(
alist(
blooms_std ~ dnorm( mu , sigma ) ,
mu <- a + bw*water_cent + bs*shade_cent + bws*water_cent*shade_cent ,
a ~ dnorm( 0.5 , 0.25 ) ,
bw ~ dnorm( 0 , 0.25 ) ,
bs ~ dnorm( 0 , 0.25 ) ,
bws ~ dnorm( 0 , 0.25 ) ,
sigma ~ dexp( 1 )
) ,
data=d )

par(mfrow=c(1,3))
for ( s in -1:1 ) {
idx <- which( d$shade_cent==s )
plot( d$water_cent[idx] , d$blooms_std[idx] , xlim=c(-1,1) , ylim=c(0,1) ,
xlab="water" , ylab="blooms" , pch=16 , col=rangi2 )
mu <- link( m8.6 , data=data.frame( shade_cent=s , water_cent=-1:1 ) )
for ( i in 1:20 ) lines( -1:1 , mu[i,] , col=col.alpha("black",0.3) )
}

8H1. Return to the data(tulips) example in the chapter. Now include the bed variable as a predictor in the interaction model. Don’t interact bed with the other predictors; just include it as a main effect. Note that bed is categorical. So to use it properly, you will need to either construct dummy variables or rather an index variable, as explained in Chapter 5.

data(tulips)
d <- tulips
str(d)
## 'data.frame':    27 obs. of  4 variables:
##  $ bed   : Factor w/ 3 levels "a","b","c": 1 1 1 1 1 1 1 1 1 2 ...
##  $ water : int  1 1 1 2 2 2 3 3 3 1 ...
##  $ shade : int  1 2 3 1 2 3 1 2 3 1 ...
##  $ blooms: num  0 0 111 183.5 59.2 ...
pairs(d)

d$shade.c <- d$shade - mean(d$shade)
d$water.c <- d$water - mean(d$water)

d$bed.idx <- coerce_index(d$bed)

m1 <- map(
  alist(
    blooms ~ dnorm( mu , sigma ) ,
    mu <- a + bW*water.c + bS*shade.c + bWS*water.c*shade.c ,
    a ~ dnorm( 130 , 100 ) ,
    bW ~ dnorm( 0 , 100 ) ,
    bS ~ dnorm( 0 , 100 ) ,
    bWS ~ dnorm( 0 , 100 ) ,
    sigma ~ dunif( 0 , 100 )
  ) ,
  data=d ,
  start=list(a=mean(d$blooms),bW=0,bS=0,bWS=0,sigma=sd(d$blooms)) )

precis(m1,depth=2)
##            mean        sd      5.5%     94.5%
## a     129.00797  8.670771 115.15041 142.86554
## bW     74.95946 10.601997  58.01542  91.90350
## bS    -41.14054 10.600309 -58.08188 -24.19920
## bWS   -51.87265 12.948117 -72.56625 -31.17906
## sigma  45.22497  6.152982  35.39132  55.05863
m2 <- map(
  alist(
    blooms ~ dnorm( mu , sigma ) ,
    mu <- a[bed.idx] + bW*water.c + bS*shade.c + bWS*water.c*shade.c ,
    a[bed.idx] ~ dnorm( 130 , 100 ) ,
    bW ~ dnorm( 0 , 100 ) ,
    bS ~ dnorm( 0 , 100 ) ,
    bWS ~ dnorm( 0 , 100 ) ,
    sigma ~ dunif( 0 , 100 )
  ) ,
  data=d ,
  start=list(a=c(mean(d$blooms),mean(d$blooms),mean(d$blooms)),bW=0,bS=0,bWS=0,sigma=sd(d$blooms)),
  method="Nelder-Mead" ,
  control=list(maxit=1e4))

precis(m2,depth=2)
##            mean        sd      5.5%     94.5%
## a[1]   97.68266 12.950536  76.98520 118.38012
## a[2]  142.32932 12.949847 121.63296 163.02568
## a[3]  146.97090 12.949927 126.27442 167.66739
## bW     75.14717  9.197126  60.44839  89.84596
## bS    -41.24262  9.195946 -55.93952 -26.54573
## bWS   -52.20443 11.239674 -70.16760 -34.24126
## sigma  39.17891  5.332924  30.65587  47.70195
compare(m1,m2)
##        WAIC        SE    dWAIC     dSE    pWAIC    weight
## m2 293.6245  9.870758 0.000000      NA 9.278819 0.8372968
## m1 296.9010 10.870104 3.276502 8.28333 7.034475 0.1627032

8H5. Consider the data(Wines2012) data table. These data are expert ratings of 20 different French and American wines by 9 different French and American judges. Your goal is to model score, the subjective rating assigned by each judge to each wine. I recommend standardizing it. In this problem, consider only variation among judges and wines. Construct index variables of judge and wine and then use these index variables to construct a linear regression model. Justify your priors. You should end up with 9 judge parameters and 20 wine parameters. Plot the parameter estimates. How do you interpret the variation among individual judges and individual wines? Do you notice any patterns, just by plotting the differences? Which judges gave the highest/lowest ratings? Which wines were rated worst/best on average?

data(Wines2012)
d = Wines2012

d2 = list(S = standardize(d$score),
          judge = as.integer(d$judge),
          wine = as.integer(d$wine))

#model_h5 <- ulam(
#    alist(
 #       S ~ dnorm(mu, sigma),
 #       mu <- a[judge] + b[wine],
 #       a[judge] ~ dnorm(0, 0.5),
 #       b[wine] ~ dnorm(0, 0.5),
 #       sigma ~ dexp(1)
        
 #   ),
  #  data = d2,
  #  chains = 4 ,
  #  cores = 4
#)

#precis(model_h5, 2)

#traceplot(model_h5)

# tried running above code but was getting error hence I had to comment it. I also tried fixing the issue but nothing worked.