#################################################
#### Run the model on simulated data
#################################################
#### Load other libraries required
library(MCMCpack)
#### Set up a network
observations <- 200
numberOfMultipleClassifications <- 50
W <- matrix(rbinom(observations * numberOfMultipleClassifications, 1, 0.05),
ncol = numberOfMultipleClassifications)
numberOfActorsWithNoPeers <- sum(apply(W, 1, function(x) { sum(x) == 0 }))
peers <- sample(1:numberOfMultipleClassifications, numberOfActorsWithNoPeers,
TRUE)
actorsWithNoPeers <- which(apply(W, 1, function(x) { sum(x) == 0 }))
for(i in 1:numberOfActorsWithNoPeers) {
W[actorsWithNoPeers[i], peers[i]] <- 1
}
W <- t(apply(W, 1, function(x) { x / sum(x) }))
#### Set up a spatial structure
numberOfSpatialAreas <- 100
factor = sample(1:numberOfSpatialAreas, observations, TRUE)
spatialAssignment = matrix(NA, ncol = numberOfSpatialAreas,
nrow = observations)
for(i in 1:length(factor)){
for(j in 1:numberOfSpatialAreas){
if(factor[i] == j){
spatialAssignment[i, j] = 1
} else {
spatialAssignment[i, j] = 0
}
}
}
gridAxis = sqrt(numberOfSpatialAreas)
easting = 1:gridAxis
northing = 1:gridAxis
grid = expand.grid(easting, northing)
numberOfRowsInGrid = nrow(grid)
distance = as.matrix(dist(grid))
squareSpatialNeighbourhoodMatrix = array(0, c(numberOfRowsInGrid,
numberOfRowsInGrid))
squareSpatialNeighbourhoodMatrix[distance==1] = 1
#### Generate the covariates and response data
X <- matrix(rnorm(2 * observations), ncol = 2)
colnames(X) <- c("x1", "x2")
beta <- c(2, -2, 2)
spatialRho <- 0.5
spatialTauSquared <- 2
spatialPrecisionMatrix = spatialRho *
(diag(apply(squareSpatialNeighbourhoodMatrix, 1, sum)) -
squareSpatialNeighbourhoodMatrix) + (1 - spatialRho) *
diag(rep(1, numberOfSpatialAreas))
spatialCovarianceMatrix = solve(spatialPrecisionMatrix)
spatialPhi = mvrnorm(n = 1, mu = rep(0, numberOfSpatialAreas),
Sigma = (spatialTauSquared * spatialCovarianceMatrix))
sigmaSquaredU <- 2
uRandomEffects <- rnorm(numberOfMultipleClassifications, mean = 0,
sd = sqrt(sigmaSquaredU))
logit <- cbind(rep(1, observations), X) %*% beta +
spatialAssignment %*% spatialPhi + W %*% uRandomEffects
prob <- exp(logit) / (1 + exp(logit))
trials <- rep(50, observations)
Y <- rbinom(n = observations, size = trials, prob = prob)
data <- data.frame(cbind(Y, X))
#### Run the model
formula <- Y ~ x1 + x2
if (FALSE) model <- uniNetLeroux(formula = formula, data = data,
family="binomial", W = W,
spatialAssignment = spatialAssignment,
squareSpatialNeighbourhoodMatrix = squareSpatialNeighbourhoodMatrix,
trials = trials, numberOfSamples = 10000,
burnin = 10000, thin = 10, seed = 1)
Run the code above in your browser using DataLab