# NOT RUN {
library(rethinking)
data(chimpanzees)
d <- chimpanzees
d$recipient <- NULL # get rid of NAs
# model 4 from chapter 12 of the book
m12.4 <- map2stan(
alist(
pulled_left ~ dbinom( 1 , p ) ,
logit(p) <- a + a_actor[actor] + (bp + bpC*condition)*prosoc_left ,
a_actor[actor] ~ dnorm( 0 , sigma_actor ),
a ~ dnorm(0,10),
bp ~ dnorm(0,10),
bpC ~ dnorm(0,10),
sigma_actor ~ dcauchy(0,1)
) ,
data=d , warmup=1000 , iter=4000 , chains=4 )
# posterior predictions for a particular actor
chimp <- 2
d.pred <- list(
prosoc_left = c(0,1,0,1), # right/left/right/left
condition = c(0,0,1,1), # control/control/partner/partner
actor = rep(chimp,4)
)
link.m12.4 <- link( m12.4 , data=d.pred )
apply( link.m12.4 , 2 , mean )
apply( link.m12.4 , 2 , PI )
# posterior predictions marginal of actor
# here we replace the varying intercepts samples
# with simulated values
# replace varying intercept samples with simulations
post <- extract.samples(m12.4)
a_actor_sims <- rnorm(7000,0,post$sigma_actor)
a_actor_sims <- matrix(a_actor_sims,1000,7)
# fire up link
# note use of replace list
link.m12.4 <- link( m12.4 , n=1000 , data=d.pred ,
replace=list(a_actor=a_actor_sims) )
# summarize
apply( link.m12.4 , 2 , mean )
apply( link.m12.4 , 2 , PI )
# }
Run the code above in your browser using DataLab