# --- Example: Simulation (Binary + Poly + Testlets) ---
set.seed(2025)
N <- 100; J <- 20
# 1. Generate Parameters
theta <- rnorm(N, 0, 1)
gamma_1 <- rnorm(N, 0, 0.5) # Testlet 1 effect
gamma_2 <- rnorm(N, 0, 0.6) # Testlet 2 effect
a_true <- runif(J, 0.8, 1.5)
b_true <- seq(-1.5, 1.5, length.out = J)
resp_matrix <- matrix(NA, N, J)
colnames(resp_matrix) <- paste0("Item_", 1:J)
# 2. Simulate Responses
# Items 1-10: Binary Independent (Model: 2PL)
for(j in 1:10) {
p <- 1 / (1 + exp(-a_true[j] * (theta - b_true[j])))
resp_matrix[,j] <- rbinom(N, 1, p)
}
# Items 11-15: Poly Independent (Model: GRM)
for(j in 11:15) {
thresh <- sort(c(b_true[j] - 0.7, b_true[j] + 0.7))
p1 <- 1 / (1 + exp(-a_true[j] * (theta - thresh[1])))
p2 <- 1 / (1 + exp(-a_true[j] * (theta - thresh[2])))
probs <- cbind(1-p1, p1-p2, p2)
resp_matrix[,j] <- apply(probs, 1, function(p) sample(0:2, 1, prob=p))
}
# Items 16-17: Binary Testlet 1 (Model: 2PLT)
for(j in 16:17) {
eff_theta <- theta + gamma_1
p <- 1 / (1 + exp(-a_true[j] * (eff_theta - b_true[j])))
resp_matrix[,j] <- rbinom(N, 1, p)
}
# Items 18-20: Poly Testlet 2 (Model: GRT)
for(j in 18:20) {
eff_theta <- theta + gamma_2
thresh <- sort(c(b_true[j] - 0.5, b_true[j] + 0.5))
p1 <- 1 / (1 + exp(-a_true[j] * (eff_theta - thresh[1])))
p2 <- 1 / (1 + exp(-a_true[j] * (eff_theta - thresh[2])))
probs <- cbind(1-p1, p1-p2, p2)
resp_matrix[,j] <- apply(probs, 1, function(p) sample(0:2, 1, prob=p))
}
df_sim <- as.data.frame(resp_matrix)
# 3. Create Item Specification
# STRICT naming: Independent=2PL/GRM, Testlet=2PLT/GRT
spec <- data.frame(
item = colnames(df_sim),
model = c(rep("2PL", 10), rep("GRM", 5), rep("2PLT", 2), rep("GRT", 3)),
testlet = c(rep(NA, 15), rep("T1", 2), rep("T2", 3)),
stringsAsFactors = FALSE
)
# 4. Run Estimation
res <- irt_trt(df_sim, spec, method = "EM",
control = list(max_iter = 20, verbose = FALSE))
head(res$item_params)
head(res$person_params)
Run the code above in your browser using DataLab