# Number of groups
M <- 10
# size of each group
N <- rep(20,M)
# covariates
X <- cbind(rnorm(sum(N),0,5),rpois(sum(N),7))
# network formation model parameter
rho <- c(-0.8, 0.2, -0.1)
# individual effects
beta <- c(2, 1, 1.5, 5, -3)
# endogenous effects
alpha <- 0.4
# std-dev errors
se <- 1
# network
tmp <- c(0, cumsum(N))
X1l <- lapply(1:M, function(x) X[c(tmp[x] + 1):tmp[x+1],1])
X2l <- lapply(1:M, function(x) X[c(tmp[x] + 1):tmp[x+1],2])
dist.net <- function(x, y) abs(x - y)
X1.mat <- lapply(1:M, function(m) {
matrix(kronecker(X1l[[m]], X1l[[m]], FUN = dist.net), N[m])})
X2.mat <- lapply(1:M, function(m) {
matrix(kronecker(X2l[[m]], X2l[[m]], FUN = dist.net), N[m])})
Xnet <- as.matrix(cbind("Const" = 1,
"dX1" = mat.to.vec(X1.mat),
"dX2" = mat.to.vec(X2.mat)))
ynet <- Xnet %*% rho
ynet <- c(1*((ynet + rlogis(length(ynet))) > 0))
G0 <- vec.to.mat(ynet, N, normalise = FALSE)
# normalise
G0norm <- norm.network(G0)
# Matrix GX
GX <- peer.avg(G0norm, X)
# simulate the dependent variable use an external package
y <- simSAR(~ X + GX, Glist = G0norm, parms = c(alpha, beta),
epsilon = rnorm(sum(N), sd = se))
Gy <- y$Gy
y <- y$y
# build dataset
dataset <- as.data.frame(cbind(y, X, Gy, GX))
colnames(dataset) <- c("y","X1","X2", "Gy", "GX1", "GX2")
nNet <- nrow(Xnet) # network formation model sample size
Aobs <- sample(1:nNet, round(0.3*nNet)) # We observed 30%
# We can estimate rho using the gml function from the stats package
logestim <- glm(ynet[Aobs] ~ -1 + Xnet[Aobs,], family = binomial(link = "logit"))
slogestim <- summary(logestim)
rho.est <- logestim$coefficients
rho.var <- slogestim$cov.unscaled # we also need the covariance of the estimator
d.logit <- lapply(1:M, function(x) {
out <- 1/(1 + exp(-rho.est[1] - rho.est[2]*X1.mat[[x]] -
rho.est[3]*X2.mat[[x]]))
diag(out) <- 0
out})
smm.logit <- smmSAR(y ~ X1 + X2, dnetwork = d.logit, contextual = TRUE,
smm.ctr = list(R = 100L, print = TRUE), data = dataset)
summary(smm.logit, dnetwork = d.logit, data = dataset)
Run the code above in your browser using DataLab