library(brms)
library(reshape2)
#Init
data(mtcars)
chains<-4
iter<-2000
warmup<-iter/2
samples<-(iter-warmup)*chains
#Fit model to predict latent variable horse power (hp) by the number of cylinders (cyl)
fit_hp<-brm(hp~cyl, data=mtcars, family=gaussian(), chains=chains, iter=iter, warmup=warmup)
fit_mpg<-brm(mpg ~ hp, data = mtcars, chains=chains, iter=iter, warmup=warmup)
# Draws from posterior predictive distribution of latent variable
post_pred_hp<-posterior_predict(fit_hp, newdata=data.frame(cyl=c(10,4)))
#Create input data from predictions of latent variable
newdata_mpg<-data.frame(hp=c(post_pred_hp[,1],post_pred_hp[,2]),
cyl=c(rep(10,samples),rep(4,samples)))
#Draws from posterior predictive distribution for all samples from posterior predictive distribution of the previous model
post_pred_mpg<-posterior_predict(fit_mpg,newdata=newdata_mpg)
post_pred_mpg<-cbind(melt(post_pred_mpg[,1:samples])$value,melt(post_pred_mpg[,(samples+1):ncol(post_pred_mpg)])$value)