# \donttest{
set.seed(123)
M <- 5 # Number of sub-groups
nvec <- round(runif(M, 100, 200)) # Random group sizes
n <- sum(nvec) # Total number of individuals
# Adjacency matrix for each group
A <- list()
for (m in 1:M) {
nm <- nvec[m] # Size of group m
Am <- matrix(0, nm, nm) # Empty adjacency matrix
max_d <- 30 # Maximum number of friends
for (i in 1:nm) {
tmp <- sample((1:nm)[-i], sample(0:max_d, 1)) # Sample friends
Am[i, tmp] <- 1 # Set friendship links
}
A[[m]] <- Am # Add to the list
}
Anorm <- norm.network(A) # Row-normalization of the adjacency matrices
# Covariates (X)
X <- cbind(rnorm(n, 1, 3), rexp(n, 0.4)) # Random covariates
# Two groups based on first covariate
group <- 1 * (X[,1] > 0.95) # Assign to groups based on x1
# Networks: Define peer effects based on group membership
# The networks should capture:
# - Peer effects of `0` on `0`
# - Peer effects of `1` on `0`
# - Peer effects of `0` on `1`
# - Peer effects of `1` on `1`
G <- list()
cums <- c(0, cumsum(nvec)) # Cumulative indices for groups
for (m in 1:M) {
tp <- group[(cums[m] + 1):(cums[m + 1])] # Group membership for group m
Am <- A[[m]] # Adjacency matrix for group m
# Define networks based on peer effects
G[[m]] <- norm.network(list(Am * ((1 - tp) %*% t(1 - tp)),
Am * ((1 - tp) %*% t(tp)),
Am * (tp %*% t(1 - tp)),
Am * (tp %*% t(tp))))
}
# Parameters for the model
lambda <- c(0.2, 0.3, -0.15, 0.25)
Gamma <- c(4.5, 2.2, -0.9, 1.5, -1.2)
delta <- rep(c(2.6, 1.47, 0.85, 0.7, 0.5), 2) # Repeated values for delta
# Prepare data for the model
data <- data.frame(X, peer.avg(Anorm, cbind(x1 = X[,1], x2 = X[,2])))
colnames(data) = c("x1", "x2", "gx1", "gx2") # Set column names
# Simulate outcomes using the `simcdnet` function
ytmp <- simcdnet(formula = ~ x1 + x2 + gx1 + gx2, Glist = G, Rbar = rep(5, 2),
lambda = lambda, Gamma = Gamma, delta = delta, group = group,
data = data)
y <- ytmp$y
# Plot histogram of the simulated outcomes
hist(y, breaks = max(y) + 1)
# Display frequency table of the simulated outcomes
table(y)
# }
Run the code above in your browser using DataLab