library(BMA)
library(mvtnorm)
##
## 1. a factor and a numeric
##
PoisReg2 <- data.frame(
x=factor(rep(0:2, 2)), x1=rep(1:2, e=3))
bicGLM2 <- bic.glm(PoisReg2, y=1:6, poisson)
newDat2 <- data.frame(
x=factor(rep(c(0, 2), 2), levels=0:2),
x1=3:6)
# NOTE: Force newDat2['x'] to have the same levels
# as PoisReg2['x']
bicGLMsim2n <- simulate(bicGLM2, nsim=5, seed=2,
newdata=newDat2[1:3,])
##
## 2. One variable: BMA returns
## a mixture of constant & linear models
##
PoisRegDat <- data.frame(x=1:2, y=c(5, 10))
bicGLMex <- bic.glm(PoisRegDat['x'],
PoisRegDat[, 'y'], poisson)
(postprob <- bicGLMex[['postprob']])
bicGLMex['mle']
# Simulate for the model data
bicGLMsim <- simulate(bicGLMex, nsim=2, seed=1)
# Simulate for new data
newDat <- data.frame(x=3:4,
row.names=paste0('f', 3:4))
bicGLMsin <- simulate(bicGLMex, nsim=3, seed=2,
newdata=newDat)
# Refit with bic.glm.matrix and confirm
# that simulate returns the same answers
bicGLMat <- bic.glm(as.matrix(PoisRegDat['x']),
PoisRegDat[, 'y'], poisson)
bicGLMatsim <- simulate(bicGLMat, nsim=3, seed=2,
newdata=newDat)
stopifnot(
all.equal(bicGLMsin, bicGLMatsim)
)
# The same problem using bic.glm.formula
bicGLMfmla <- bic.glm(y ~ x, PoisRegDat, poisson)
bicGLMfmlsim <- simulate(bicGLMfmla, nsim=3, seed=2,
newdata=newDat)
stopifnot(
all.equal(bicGLMsin, bicGLMfmlsim)
)
##
## 2a. Compute the correct answers manually
##
GLMex1 <- glm(y~x, poisson, PoisRegDat)
GLMex0 <- glm(y~1, poisson, PoisRegDat)
postProb <- bicGLMfmla$postprob
nComp <- length(postProb)
newMat <- model.matrix(~., newDat)
set.seed(2)
(rmdl <- sample(1:nComp, 3, TRUE,
postprob))
GLMsim. <- matrix(NA, 2, 3)
dimnames(GLMsim.) <- list(
rownames(newMat),
paste0('sim_', 1:3) )
sim1 <- mvtnorm::rmvnorm(2, coef(GLMex1),
vcov(GLMex1))
sim0 <- mvtnorm::rmvnorm(1, coef(GLMex0),
vcov(GLMex0))
GLMsim.[, rmdl==1] <- tcrossprod(newMat, sim1)
GLMsim.[, rmdl==2] <- tcrossprod(
newMat[, 1, drop=FALSE], sim0)
stopifnot(
all.equal(bicGLMsin[[2]], data.frame(GLMsim.),
tolerance=4*sqrt(.Machine$double.eps))
# tcrossprod numeric precision is mediocre
# for the constant model in this example.
)
Run the code above in your browser using DataLab