# \donttest{
# example of CAR spatial random effects
if (requireNamespace("sf")) {
# 1. load a shape file of counties in North Carolina
nc <- sf::st_read(system.file("shape/nc.shp", package="sf"))
# 2. generate some data according to a model with a few regression
# effects, as well as spatial random effects
gd <- generate_data(
~ reg(~ AREA + BIR74, prior=pr_normal(precision=1), name="beta") +
gen(factor = ~ spatial(NAME, graph=nc), name="vs"),
sigma.mod = pr_invchisq(df=10, scale=1),
data = nc
)
# add the generated target variable and the spatial random effects to the
# spatial dataframe object
nc$y <- gd$y
nc$vs_true <- gd$pars$vs
# 3. fit a model to the generated data, and see to what extent the
# parameters used to generate the data, gd$pars, are reproduced
sampler <- create_sampler(
y ~ reg(~ AREA + BIR74, prior=pr_normal(precision=1), name="beta") +
gen(factor = ~ spatial(NAME, graph=nc), name="vs"),
data=nc
)
sim <- MCMCsim(sampler, store.all=TRUE, n.iter=600, n.chain=2, verbose=FALSE)
(summ <- summary(sim))
nc$vs <- summ$vs[, "Mean"]
plot(nc[c("vs_true", "vs")])
plot(gd$pars$vs, summ$vs[, "Mean"]); abline(0, 1, col="red")
}
# }
Run the code above in your browser using DataLab