# How to run IRT analyses in R
# R code from https://philippmasur.de/blog/2022-05-13-irt-analyses-in-r/

# Data wrangling
library(tidyverse)

# Very comprehensive package for IRT analyses
library(mirt)

# Extension for 'mirt'
# devtools::install_github("masurp/ggmirt")
library(ggmirt)

set.seed(42)
d <- sim_irt(500, 10, discrimination = .25, seed = 42)
head(d)

unimodel <- 'F1 = 1-10'

fit3PL <- mirt(data = d,
               model = unimodel,  # alternatively, we could also just specify model = 1 in this case
               itemtype = "3PL",
               verbose = FALSE)
fit3PL

# Factor solution
summary(fit3PL)

params3PL <- coef(fit3PL, IRTpars = TRUE, simplify = TRUE)
round(params3PL$items, 2) # g = c = guessing parameter

M2(fit3PL)

itemfit(fit3PL)

itemfit(fit3PL, fit_stats = "infit") # typical for Rasch modeling

itemfitPlot(fit3PL)

head(personfit(fit3PL))

personfit(fit3PL) %>%
  reframe(infit.outside = prop.table(table(z.infit > 1.96 | z.infit < -1.96)),
          outfit.outside = prop.table(table(z.outfit > 1.96 | z.outfit < -1.96))) # lower row = non-fitting people

personfitPlot(fit3PL)

itempersonMap(fit3PL)

tracePlot(fit3PL)

tracePlot(fit3PL, facet = F, legend = T) + scale_color_brewer(palette = "Set3")

# Plotting only individual items
tracePlot(fit3PL,items = c(1:3), facet = F, legend = T) + scale_color_brewer(palette = "Set2")

itemInfoPlot(fit3PL) + scale_color_brewer(palette = "Set3")

itemInfoPlot(fit3PL, facet = T)

testInfoPlot(fit3PL, adj_factor = 2)

scaleCharPlot(fit3PL)

score <- fscores(fit3PL)
sumscore <- rowSums(d)
cor.test(score, sumscore)

fit2PL <- mirt(d, 1, itemtype = "2PL", verbose = F)
fit2PL

anova(fit2PL, fit3PL)

coef(fit2PL, IRTpars = TRUE, simplify = TRUE)

tracePlot(fit2PL, theta_range = c(-5, 5), facet = F, legend = T) +
  scale_color_brewer(palette = "Set3") +
  labs(title = "2PL - Traceplot")

fitRasch <- mirt(d, 1, itemtype = "Rasch", verbose = T)

fitRasch

anova(fitRasch, fit2PL)

coef(fitRasch, IRTpars = TRUE, simplify = TRUE)

tracePlot(fitRasch, theta_range = c(-5, 5), facet = F, legend = T) +
  scale_color_brewer(palette = "Set3") +
  labs(title = "1PL - Traceplot")

itempersonMap(fitRasch)

subset1 <- d %>%
  select(V2, V10, V3, V4, V7)
subset2 <- d %>%
  select(V6, V8, V5, V1, V9)

test1 <- mirt(subset1, 1, itemtype = "Rasch", verbose = F)
test2 <- mirt(subset2, 1, itemtype = "Rasch", verbose = F)

testInfoCompare(test1, test2)

cor.test(fscores(test1), fscores(fitRasch))

cor.test(fscores(test2), fscores(fitRasch))
