The hardware and bandwidth for this mirror is donated by dogado GmbH, the Webhosting and Full Service-Cloud Provider. Check out our Wordpress Tutorial.
If you wish to report a bug, or if you are interested in having us mirror your free-software or open-source project, please feel free to contact us at mirror[@]dogado.de.

Package {IRTC}


Type: Package
Title: Marginal Maximum Likelihood Estimation for Item Response Models
Version: 1.1.1
Date: 2026-07-17
Description: Self-contained marginal maximum likelihood (MML) estimation for unidimensional and multidimensional item response models, including the Rasch / one-parameter logistic, partial credit, rating scale, two-parameter logistic and generalised partial credit models, with latent regression, multiple groups and case weights. A parallelised, dimension-factorised streaming estimation engine supports large between-item (simple-structure) multidimensional models with bounded memory and an opt-in controlled-accuracy quadrature mode that reports a measured approximation error. A usability layer serves non-specialists and automated pipelines: one-stop estimation from common file formats ('Excel', delimited text, 'SPSS', 'Stata', 'SAS') with automatic cleaning and answer-key scoring, pre-estimation data checks, classical item statistics and item fit, plain-language quality ratings, bilingual (English/Chinese) output, spreadsheet exports for item banking and cross-year linking, audience-specific 'Word'/'HTML' reports, and machine-readable results with structured error conditions. Methods follow Adams, Wilson and Wang (1997) <doi:10.1177/0146621697211001>.
License: GPL-2 | GPL-3 [expanded from: GPL (≥ 2)]
Copyright: See file inst/COPYRIGHTS.
URL: https://github.com/weiandata/IRTC
BugReports: https://github.com/weiandata/IRTC/issues
Depends: R (≥ 3.5.0)
Imports: Rcpp, stats, utils, methods, MASS, tools, graphics, grDevices
Suggests: testthat (≥ 3.0.0), mvtnorm, sfsmisc, readxl, writexl, haven, openxlsx, officer, jsonlite
LinkingTo: Rcpp, RcppArmadillo
Encoding: UTF-8
NeedsCompilation: yes
Packaged: 2026-07-17 09:53:17 UTC; makunxiang
Author: Kunxiang Ma [aut, cre], WEIAN DATA TECH (Beijing) Co., Ltd. [cph, fnd]
Maintainer: Kunxiang Ma <makunxiang@weiandata.com>
Repository: CRAN
Date/Publication: 2026-07-24 10:30:22 UTC

Marginal Maximum Likelihood Estimation for Item Response Models

Description

A self-contained marginal maximum likelihood estimation package for unidimensional and multidimensional item response models. It supports Rasch / 1PL, partial credit, rating scale, 2PL and generalized partial credit models, latent regression, multiple groups, case weights, and a bounded-memory streaming engine for large simple-structure models.

Details

Two entry points are provided.

For statisticians, the expert functions irtc.mml and irtc.mml.2pl return an object of class irtc with summary, print, logLik, anova and plot methods.

For non-specialists and automated pipelines, the one-stop function irtc reads data from common file formats (irtc_read), scores raw responses (irtc_score), checks the data (irtc_check_data) and enriches the fitted model with classical statistics (irtc_ctt), item fit (irtc_itemfit) and plain-language quality ratings (irtc_quality). Results can be exported as three Excel workbooks (irtc_excel), audience-specific Word/HTML reports (irtc_report), a layered text summary (plain_summary) or machine-readable structures (irtc_results, irtc_json; schema reference in inst/llms.txt). User-facing output is bilingual; see irtc_lang.

Author(s)

Kunxiang Ma and WEIAN DATA TECH (Beijing) Co., Ltd.

See Also

irtc, irtc.mml, irtc.mml.2pl


Simulated Polytomous Item Response Data

Description

A simulated dataset of polytomous item responses suitable for fitting partial credit and generalised partial credit models, provided as an example dataset for IRTC.

Usage

data(data.gpcm)

Format

A data frame with 392 persons (rows) and 3 polytomously scored items (columns Comfort, Work, Benefit), each scored in four ordered categories 0, 1, 2, 3.

Details

The data were simulated from a partial credit model with three step parameters per item. The generating script is ‘scripts/gen_data.R’ in the package sources.

Source

Simulated by IRTC. See ‘scripts/gen_data.R’ in the package sources for the reproducible generating code.


Simulated Multiple-Choice Item Response Data

Description

A simulated dataset of multiple-choice item responses provided in both raw and scored form, provided as an example dataset for IRTC.

Usage

data(data.mc)

Format

A list with two components:

raw

A character matrix (143 persons x 30 items) of raw multiple-choice responses coded "A""D", with "9" denoting an omitted or not-reached response.

scored

A data frame of the corresponding dichotomously scored (0/1) responses, where 1 marks the keyed (correct) option.

Details

Correctness was simulated under a Rasch model; raw responses were then built from a randomly assigned answer key with distractors drawn at random. The generating script is ‘scripts/gen_data.R’ in the package sources.

Source

Simulated by IRTC. See ‘scripts/gen_data.R’ in the package sources for the reproducible generating code.


Simulated Dichotomous Rasch Data

Description

A simulated dataset of dichotomous (0/1) item responses generated under the Rasch model, provided as an example dataset for IRTC.

Usage

data(data.sim.rasch)

Format

A matrix with 2000 persons (rows) and 40 dichotomous items (columns), with entries coded 0 or 1.

Details

The data were simulated with person abilities drawn from a standard normal distribution and item difficulties spread evenly over [-2.2, 2.2]. The generating script is ‘scripts/gen_data.R’ in the package sources.

Source

Simulated by IRTC. See ‘scripts/gen_data.R’ in the package sources for the reproducible generating code.


One-Stop Item Response Model Estimation

Description

Reads data from a file or R object, cleans it, optionally scores raw multiple-choice responses against an answer key, checks it, estimates the requested item response model and enriches the result with classical item statistics, item fit and plain-language quality ratings.

Designed for non-specialists and automated callers; professional users keep full control because all additional arguments are passed unchanged to irtc.mml (for "1PL", "PCM", "PCM2", "RSM") or irtc.mml.2pl (for "2PL", "GPCM").

Usage

irtc(data, model, key = NULL, rules = NULL, q = NULL,
    on_mismatch = c("warn", "error"),
    rare_categories = c("collapse", "prior"), id = NULL, weights = NULL,
    sheet = 1, missing_codes = c(-9, -99, 99, 999), check = TRUE,
    quality = TRUE, verbose = TRUE, ...)

Arguments

data

A file path (.xlsx, .xls, .csv, .tsv, .txt, .dat, .sav, .por, .dta, .sas7bdat, .xpt), a data frame, a matrix, or an object returned by irtc_read.

model

Required. One of "1PL" (alias "Rasch"), "2PL", "PCM", "PCM2", "RSM", "GPCM". Case-insensitive.

key

An optional answer key for raw responses: a named vector or a key-file path (optionally with a partial-answer column); see irtc_score.

rules

An optional partial-credit scoring table or a path to one; see irtc_score.

q

An optional Q (item-by-dimension) matrix: a file path, data frame, matrix, or an object from irtc_read_q. The Q matrix is aligned with the data via irtc_align_q and passed to the estimation as Q; its dimension names label the person-level output. If Q is also supplied through ..., the explicit Q wins and a warning (W419) is raised.

on_mismatch

How to handle items that differ between the Q matrix and the data; see irtc_align_q.

rare_categories

How to handle score categories nobody reached (nobody fully correct / partially correct / wrong). "collapse" (default): merge unobserved categories into their lower neighbour; the mapping is logged (W425) and annotated in the item output (categories_unobserved, categories_collapsed, declared vs observed maximum score). "prior": keep the observed category structure; thresholds of in-range empty categories get a N(0, 4) prior (models "1PL", "PCM") or are fixed at the prior mean 0 (models "2PL", "GPCM", whose estimation core does not evaluate priors); such thresholds are marked prior_dominated in the output. Categories above the observed maximum have no parameter in either mode and are reported as a reduced maximum score. Items answered by nobody are removed (W410) but keep an annotated row in irtc_results.

id

An optional person identifier column (name or index); passed to irtc_read.

weights

An optional sampling weight column (name or index); passed to irtc_read. Common weight column names are also detected automatically. The weights are used as pweights in the estimation; if pweights is also supplied through ..., the explicit pweights wins and a warning (W418) is raised.

sheet

Excel sheet to read (number or name).

missing_codes

Numeric values recoded to NA during cleaning; see irtc_read.

check

Logical: stop with a structured error if irtc_check_data finds any error-level issue?

quality

Logical: attach CTT statistics, item fit and quality ratings to the result?

verbose

Logical: print estimation progress?

...

Further arguments passed to irtc.mml or irtc.mml.2pl (e.g. group, pweights, Q, control).

Details

Items without any observed responses or without variance are removed before estimation (with a warning of class irtc_warning_estimation). All errors raised by the usability layer are structured conditions with fields code, reason and fix; see the package file inst/llms.txt for the full list of codes.

The language of user-facing output is controlled by options(irtc.lang = "zh") (default) or "en".

Value

An object of class irtc (see irtc.mml) with an additional list component usability containing model, data_log (cleaning log), check (the irtc_check_data result), removed_items, ctt, itemfit and quality.

See Also

irtc_read, irtc_check_data, plain_summary, irtc_excel, irtc_report, irtc_results

Examples

set.seed(1)
theta <- rnorm(150)
resp <- as.data.frame(sapply(seq(-1, 1, length.out = 5), function(b) {
    as.numeric(runif(150) < plogis(theta - b))
}))
colnames(resp) <- paste0("I", 1:5)

mod <- irtc(resp, model = "1PL", verbose = FALSE)
plain_summary(mod, lang = "en")
mod$usability$quality

Marginal Maximum Likelihood Estimation of Fixed-Slope Item Response Models

Description

Estimates unidimensional and multidimensional fixed-slope item response models by marginal maximum likelihood (MML). Supported models include the Rasch / 1PL model, the partial credit model ("PCM", "PCM2") and the rating scale model ("RSM"). Latent regression on covariates, multiple groups, case weights and user-specified design matrices are supported.

Usage

irtc.mml(resp, Y = NULL, group = NULL, irtmodel = "1PL",
   formulaY = NULL, dataY = NULL, ndim = 1, pid = NULL,
   xsi.fixed = NULL, xsi.inits = NULL, beta.fixed = NULL, beta.inits = NULL,
   variance.fixed = NULL, variance.inits = NULL, est.variance = TRUE,
   constraint = "cases", A = NULL, B = NULL, B.fixed = NULL, Q = NULL,
   est.slopegroups = NULL, E = NULL, pweights = NULL,
   userfct.variance = NULL, variance.Npars = NULL, item.elim = TRUE,
   verbose = TRUE, control = list())

## S3 method for class 'irtc'
summary(object, file = NULL, ...)

## S3 method for class 'irtc'
print(x, ...)

## S3 method for class 'irtc'
logLik(object, ...)

## S3 method for class 'irtc'
anova(object, ...)

Arguments

resp

A data frame or matrix of polytomous or dichotomous item responses. Missing responses are coded NA.

Y

An optional matrix of covariates for the latent regression.

group

An optional vector of integer group identifiers for multiple-group estimation.

irtmodel

The estimated item response model. One of "1PL", "PCM", "PCM2" or "RSM".

formulaY

An optional formula for the latent regression in conjunction with dataY.

dataY

An optional data frame of covariates used together with formulaY.

ndim

The number of latent dimensions (used when no Q or B is supplied).

pid

An optional vector of person identifiers.

xsi.fixed

An optional matrix with two columns for fixing item parameters: parameter index and fixed value.

xsi.inits

An optional matrix of initial item parameter values.

beta.fixed

An optional matrix for fixing regression coefficients, or FALSE to estimate all.

beta.inits

An optional matrix of initial regression coefficients.

variance.fixed

An optional matrix for fixing entries of the covariance matrix.

variance.inits

An optional initial covariance matrix.

est.variance

Logical: should the covariance matrix be estimated?

constraint

Identification constraint, either "cases" or "items".

A

An optional design array for the item intercepts.

B

An optional design array for the (fixed) item slopes / scoring.

B.fixed

An optional matrix for fixing entries of the loading array B.

Q

An optional loading (Q-) matrix mapping items to dimensions.

est.slopegroups

An optional vector grouping items with common slope design (advanced use).

E

An optional design array used together with est.slopegroups.

pweights

An optional vector of person (case) weights.

userfct.variance

An optional user function imposing constraints on the covariance matrix.

variance.Npars

The number of estimated parameters in a user-constrained covariance matrix.

item.elim

Logical: should items with no observed responses in a category be eliminated?

verbose

Logical: print progress during estimation?

control

A list of control arguments for the estimation (e.g. maxiter, conv, snodes, nodes). Performance-related elements: n_threads (threads for the parallel E-step; default and maximum = 2), fast (logical, default FALSE; opt-in approximate mode that prunes negligible-weight quadrature nodes), and fast_threshold (pruning cutoff, default 1e-6).

object, x

An object of class irtc as produced by irtc.mml.

file

An optional file name; if supplied, summary output is written there.

...

Further arguments passed to methods.

Value

An object of class irtc, a list with (among others) the components:

xsi

A data frame of estimated item parameters and standard errors.

beta

The estimated latent regression coefficients.

variance

The estimated covariance matrix of the latent dimensions.

person

A data frame of person parameter estimates (EAP) and related statistics.

EAP.rel

The EAP reliability per dimension.

deviance

The deviance (-2 \log L) at the solution.

ic

A list of information criteria (AIC, BIC, ...).

CALL

The matched call.

References

Adams, R. J., Wilson, M., & Wang, W. C. (1997). The multidimensional random coefficients multinomial logit model. Applied Psychological Measurement, 21(1), 1–23. doi:10.1177/0146621697211001

See Also

irtc.mml.2pl for models with estimated item slopes.

Examples


#############################################################################
# EXAMPLE 1: Unidimensional Rasch model
#############################################################################

data(data.sim.rasch)
mod1 <- irtc.mml(resp = data.sim.rasch)
summary(mod1)

#############################################################################
# EXAMPLE 2: Partial credit model
#############################################################################

data(data.gpcm)
mod2 <- irtc.mml(resp = data.gpcm, irtmodel = "PCM")
summary(mod2)


Marginal Maximum Likelihood Estimation of Slope (Discrimination) Item Response Models

Description

Estimates unidimensional and multidimensional item response models with estimated item slopes (discriminations) by marginal maximum likelihood (MML). Supported models are the two-parameter logistic model ("2PL"), the generalized partial credit model ("GPCM"), their design-matrix and slope-group variants ("GPCM.design", "2PL.groups", "GPCM.groups").

Usage

irtc.mml.2pl(resp, Y = NULL, group = NULL, irtmodel = "2PL",
   formulaY = NULL, dataY = NULL, ndim = 1, pid = NULL,
   xsi.fixed = NULL, xsi.inits = NULL, beta.fixed = NULL, beta.inits = NULL,
   variance.fixed = NULL, variance.inits = NULL, est.variance = FALSE,
   A = NULL, B = NULL, B.fixed = NULL, Q = NULL, est.slopegroups = NULL,
   E = NULL, gamma.init = NULL, pweights = NULL, userfct.variance = NULL,
   variance.Npars = NULL, item.elim = TRUE, verbose = TRUE,
   method = c("auto", "grid", "streaming"), control = list())

Arguments

resp

A data frame or matrix of item responses (NA = missing).

Y

Optional covariate matrix for the latent regression.

group

Optional integer vector of group identifiers for multiple groups.

irtmodel

The estimated model: one of "2PL", "GPCM", "GPCM.design", "2PL.groups", "GPCM.groups".

formulaY

Optional formula for the latent regression (with dataY).

dataY

Optional covariate data frame used with formulaY.

ndim

Number of latent dimensions (when no Q/B is given).

pid

Optional vector of person identifiers.

xsi.fixed

Optional matrix (index, value) fixing item intercept parameters.

xsi.inits

Optional matrix of initial item parameters.

beta.fixed

Optional matrix fixing regression coefficients, or FALSE.

beta.inits

Optional matrix of initial regression coefficients.

variance.fixed

Optional matrix fixing covariance entries.

variance.inits

Optional initial covariance matrix.

est.variance

Logical: estimate the covariance matrix? (default FALSE).

A

Optional design array for item intercepts.

B

Optional design array for item slopes.

B.fixed

Optional matrix fixing entries of the slope array B.

Q

Optional loading (Q-) matrix mapping items to dimensions.

est.slopegroups

Optional vector grouping items that share a common estimated slope.

E

Optional design array used with est.slopegroups / GPCM.design.

gamma.init

Optional initial values for the estimated slope parameters.

pweights

Optional vector of person (case) weights.

userfct.variance

Optional user function constraining the covariance matrix.

variance.Npars

Number of estimated parameters in a user-constrained covariance.

item.elim

Logical: eliminate items with empty response categories?

verbose

Logical: print estimation progress?

method

Estimation engine. "grid" is the standard full-quadrature path. "streaming" routes to a dimension-factorized streaming engine for large between-item (simple-structure) multidimensional 2PL/GPCM models; it supports latent regression (Y), multiple groups (group, with per-group covariances), and case weights (pweights), but not the advanced item-design arguments (A, B, xsi.fixed, etc.), which force "grid". "auto" (default) predicts which engine is faster from (N, items, dims, nodes, unique covariate patterns) and routes accordingly (falling back to "grid" for unidimensional/small/unsupported models); the chosen engine and reasoning are returned in the routing component of the result. With case weights the result also reports the Kish effective sample size in n_eff.

control

List of control arguments (e.g. maxiter, conv, nodes, Msteps). Performance-related elements: n_threads (threads for the parallel E-step and slope M-step; default and maximum = 2), fast (logical, default FALSE; approximate mode pruning negligible-weight quadrature nodes), fast_threshold (pruning cutoff, default 1e-6), and acceleration ("none" default, or "squarem"/"Ramsay"/"Yu" to accelerate the grid EM). The streaming engine additionally accepts reg for opt-in statistical regularization (slope_penalty, slope_max, sigma_shrink, and sigma_shrink_pooled for shrinking per-group covariances toward the pooled estimate; default off), and group_structure ("full" = independent per-group covariances, default; "mean" = shared covariance with free group means).

When fast=TRUE the streaming engine prunes quadrature nodes by a calibrated mass_budget (default 1e-3): after a few full-grid burn-in iterations it drops the lowest-importance nodes holding at most that fraction of the combined prior-and-posterior mass, retained per (covariate, group) pattern and unioned so extreme responders and small groups are protected. mass_budget is a pruning budget, not a guaranteed error. The real accuracy is measured: with verify="stratified" (default) a stratified subsample (groups, high weights, extreme responders, high-missingness; verify_n, verify_seed) is run through both the full and pruned grids at the final parameters, and the per-metric error quantiles (deviance / EAP / posterior moments / one-M-step parameter change, against tol_deviance/tol_eap/tol_moment/tol_par) are returned in accuracy_report with a met verdict. refine=TRUE refits with a tighter budget until the tolerances are met.

Value

An object of class irtc (see irtc.mml) with, in addition, the estimated slope array B and the slope parameter vector. Streaming-engine fits also carry a routing component (chosen engine and reasoning) and, when fast=TRUE with verification on, an accuracy_report: a measured, stratified approximation check (per-metric error quantiles plus a met verdict), not a strict mathematical error bound.

See Also

irtc.mml for fixed-slope (Rasch / PCM / RSM) models.

Examples


data(data.sim.rasch)
mod1 <- irtc.mml.2pl(resp = data.sim.rasch, irtmodel = "2PL")
summary(mod1)

data(data.gpcm)
mod2 <- irtc.mml.2pl(resp = data.gpcm, irtmodel = "GPCM")
summary(mod2)


Pre-Estimation Data Diagnostics

Description

Checks a response data set before model estimation and returns both a human-readable report and a machine-readable issue table, so that survey staff and automated callers (e.g. AI agents) can verify data quality and act on concrete fixes.

Checked, among others: number of items and persons, non-numeric (raw) response columns, negative or non-integer values, items without responses or without variance, extreme missingness, sparse categories, persons without any responses and duplicated person IDs.

Usage

irtc_check_data(x, key = NULL, verbose = TRUE)

## S3 method for class 'irtc_check'
print(x, lang = irtc_lang(), ...)

Arguments

x

An irtc_data object, a data frame or a matrix. For the print method: an irtc_check object.

key

If an answer key will be used for scoring, pass it here so that raw text columns are reported as scorable instead of as errors.

verbose

Logical: print the result?

lang

Output language, "zh" or "en".

...

Ignored.

Value

An object of class irtc_check: a list with ok (logical: no error-level issues), n_persons, n_items, n_errors, n_warnings and issues, a data frame with columns code, severity ("error", "warning", "info"), scope, where, message_en, message_zh, fix_en, fix_zh.

See Also

irtc_read, irtc

Examples

d <- data.frame(i1 = c(0, 1, 1, 0), i2 = c(1, 1, 1, 1),
    i3 = c(0, NA, 1, -9))
chk <- irtc_check_data(d, verbose = FALSE)
chk$ok
chk$issues[, c("code", "severity", "where")]
print(chk, lang = "en")

Classical Test Theory Item Statistics

Description

Computes classical item statistics: item means and difficulty (share of the maximum score), corrected item-total (item-rest) correlations, Cronbach's alpha and alpha-if-item-deleted.

Usage

irtc_ctt(x, key = NULL)

## S3 method for class 'irtc_ctt'
print(x, lang = irtc_lang(), ...)

Arguments

x

An irtc_data object, a data frame, a matrix, or a fitted irtc model (its stored response data are used). For the print method: an irtc_ctt object.

key

An optional answer key; raw responses are scored first via irtc_score.

lang

Output language, "zh" or "en".

...

Ignored.

Value

An object of class irtc_ctt: a list with items (data frame with columns item, N, miss_rate, max_score, M, pvalue, discr, alpha_if_deleted), alpha, n_persons and n_items.

See Also

irtc_quality, irtc_itemfit

Examples

set.seed(1)
theta <- rnorm(200)
resp <- as.data.frame(sapply(seq(-1, 1, length.out = 6), function(b) {
    as.numeric(runif(200) < plogis(theta - b))
}))
ctt <- irtc_ctt(resp)
ctt$alpha
ctt$items

Export Three Excel Result Workbooks

Description

One call writes three separate .xlsx files (requires the optional openxlsx package):

  1. <prefix>_item_quality.xlsx - a plain-language item quality table (score rate, difficulty label, discrimination, fit, colour-coded overall rating, reasons and advice) plus a notes sheet explaining every column, for judging item quality without statistical training.

  2. <prefix>_item_parameters.xlsx - the IRT difficulty / discrimination table with a frozen column schema (schema_version, analysis_id, model, item_id, n_obs, p_value, slope_a, difficulty_b, se_b, tau_k), designed for cross-year anchor-item linking: files from different administrations can be merged directly on item_id.

  3. <prefix>_person_ability.xlsx - a flat person ability table (ID, number answered, raw score, EAP, standard error, percentile, T score) whose rows stay in input order so it can be pasted next to a master sample sheet.

Usage

irtc_excel(mod, dir = ".", prefix = "IRTC", lang = irtc_lang(),
    resp = NULL, overwrite = FALSE, verbose = TRUE)

irtc_param_table(mod, resp = NULL)

irtc_person_table(mod, lang = irtc_lang())

Arguments

mod

A fitted irtc model object.

dir

Output directory (created if necessary).

prefix

File name prefix.

lang

Language of headers and notes, "zh" or "en". The linking schema of file 2 is language-independent.

resp

The response data; only needed when the model object does not store it (streaming engine).

overwrite

Logical: overwrite existing files? Otherwise an error of class irtc_error_export (code E501) is raised.

verbose

Logical: print a completion message?

Value

irtc_excel invisibly returns a named character vector with the three file paths (quality, parameters, ability). irtc_param_table and irtc_person_table return the underlying data frames and work without openxlsx.

See Also

irtc, irtc_report, irtc_results

Examples

set.seed(1)
theta <- rnorm(150)
resp <- as.data.frame(sapply(seq(-1, 1, length.out = 5), function(b) {
    as.numeric(runif(150) < plogis(theta - b))
}))
mod <- irtc(resp, model = "1PL", verbose = FALSE)

## data frames behind the workbooks (no extra packages needed)
irtc_param_table(mod)
head(irtc_person_table(mod, lang = "en"))

if (requireNamespace("openxlsx", quietly = TRUE)) {
    out <- irtc_excel(mod, dir = tempdir(), overwrite = TRUE,
        verbose = FALSE)
    basename(out)
}

Item Fit Statistics (Infit and Outfit)

Description

Residual-based item fit for a fitted model: infit and outfit mean squares with Wilson-Hilferty t statistics, evaluated at the EAP person estimates. Values near 1 indicate good fit; the conventional normal range is 0.7 to 1.3.

Usage

irtc_itemfit(mod, resp = NULL)

## S3 method for class 'irtc_itemfit'
print(x, lang = irtc_lang(), ...)

Arguments

mod

A fitted irtc model object.

resp

The response data; only needed when the model object does not store it (streaming engine).

x

An irtc_itemfit object.

lang

Output language, "zh" or "en".

...

Ignored.

Value

A data frame of class irtc_itemfit with columns item, N, outfit, outfit_t, infit, infit_t.

See Also

irtc_quality, irtc_ctt

Examples

set.seed(1)
theta <- rnorm(200)
resp <- as.data.frame(sapply(seq(-1, 1, length.out = 5), function(b) {
    as.numeric(runif(200) < plogis(theta - b))
}))
mod <- irtc.mml(resp = resp, verbose = FALSE)
irtc_itemfit(mod)

Output Language of the IRTC Usability Layer

Description

Returns the current output language, "zh" (Chinese, the default) or "en" (English). Set it globally with options(irtc.lang = "en"). The language affects user-facing text (messages, printed summaries, Excel headers, reports); machine-readable schemas (irtc_results, the linking table of irtc_excel) never depend on it.

Usage

irtc_lang()

Value

"zh" or "en".

Examples

old <- options(irtc.lang = "en")
irtc_lang()
options(old)

Plain-Language Item Quality Ratings

Description

Combines classical difficulty and discrimination (irtc_ctt) with IRT item fit (irtc_itemfit) into a four-level quality rating per item - "good", "acceptable", "review", "revise" - with bilingual reasons and advice that non-specialists can act on. Negative discrimination (usually a wrong answer key) always leads to "revise".

Usage

irtc_quality(mod, resp = NULL, thresholds = NULL)

irtc_quality_thresholds()

## S3 method for class 'irtc_quality'
print(x, lang = irtc_lang(), ...)

Arguments

mod

A fitted irtc model object.

resp

The response data; only needed when the model object does not store it (streaming engine).

thresholds

An optional named list overriding entries of irtc_quality_thresholds(): p_hard (default 0.10), p_easy (0.95), discr_poor (0.15), discr_weak (0.25), fit_mild (c(0.70, 1.30)), fit_severe (c(0.50, 1.50)).

x

An irtc_quality object.

lang

Output language, "zh" or "en".

...

Ignored.

Value

A data frame of class irtc_quality with columns item, N, pvalue, discr, outfit, infit, rating, reasons_en, reasons_zh, advice_en, advice_zh, and attributes alpha (Cronbach's alpha) and thresholds. irtc_quality_thresholds() returns the default threshold list.

See Also

irtc, irtc_excel

Examples

set.seed(1)
theta <- rnorm(300)
resp <- as.data.frame(sapply(seq(-1, 1, length.out = 6), function(b) {
    as.numeric(runif(300) < plogis(theta - b))
}))
resp$noise <- rbinom(300, 1, 0.5)  # a broken item
mod <- irtc.mml(resp = resp, verbose = FALSE)
qual <- irtc_quality(mod)
qual[, c("item", "pvalue", "discr", "rating")]
print(qual, lang = "en")

Read and Clean Item Response Data from Many Formats

Description

Unified data import with automatic cleaning. Supports Excel (.xlsx, .xls; requires readxl), delimited text (.csv, .tsv, .txt, .dat; delimiter and UTF-8/GBK encoding are detected automatically), SPSS/Stata/SAS files (.sav, .por, .dta, .sas7bdat, .xpt; requires haven) and in-memory data frames, matrices and tibbles.

Every cleaning action is recorded in a bilingual log attached to the returned object, so results remain traceable.

Usage

irtc_read(x, sheet = 1, id = NULL, weights = NULL,
    missing_codes = c(-9, -99, 99, 999),
    na_strings = c("", "NA", "N/A", "n/a", ".", "*",
        "\u7f3a\u5931", "\u65e0", "\u7a7a"),
    guess_id = TRUE, guess_weights = TRUE, clean = TRUE, recode = TRUE,
    verbose = TRUE)

## S3 method for class 'irtc_data'
print(x, lang = irtc_lang(), ...)

Arguments

x

A file path or a data frame / matrix. For the print method: an irtc_data object.

sheet

Excel sheet to read (number or name).

id

Person identifier column(s), by name or index. The first is kept as the person ID; the rest are set aside. If NULL and guess_id is TRUE, common ID column names (id, pid, student number, name, etc., in English and Chinese) are detected automatically.

missing_codes

Numeric codes recoded to NA. Negative codes are always treated as missing; a positive code is only recoded in a column when it lies clearly above the observed response range, which protects e.g. a legitimate score of 99 on a 0-100 scale.

na_strings

Strings treated as missing in text columns.

weights

Sampling weight column, by name or index. If NULL and guess_weights is TRUE, common weight column names (weight, wt, pweight, "权重", "样本权重", etc., in English and Chinese) are detected automatically. The column is set aside as $weights and later used as pweights by irtc. Weights must be positive numbers; missing weights are set to 1 with a warning.

guess_id

Logical: detect the person ID column automatically?

guess_weights

Logical: detect the weight column automatically?

clean

Logical: apply the cleaning steps (drop empty rows/columns, convert numeric-like text, recode missing codes)?

recode

Logical: recode integer response categories to consecutive scores starting at 0 (e.g. a 1-5 Likert item becomes 0-4)?

verbose

Logical: print the object (including the cleaning log)?

lang

Output language, "zh" or "en".

...

Ignored.

Value

An object of class irtc_data: a list with components resp (cleaned response data frame), pid (person IDs or NULL), weights (sampling weights or NULL), dropped (set-aside non-response columns), log (cleaning log data frame with columns step, code, message_en, message_zh) and source.

See Also

irtc, irtc_score, irtc_check_data

Examples

path <- tempfile(fileext = ".csv")
writeLines(c("id,i1,i2,i3", "s1,0,1,99", "s2,1,-9,1", "s3,1,0,0"), path)
d <- irtc_read(path, verbose = FALSE)
d$resp
d$pid
print(d, lang = "en")
unlink(path)

Read a Q Matrix from a File and Align It with the Response Data

Description

irtc_read_q reads a Q (item-by-dimension) matrix from any file format supported by irtc_read (Excel, delimited text, SPSS/Stata/SAS) or from a data frame / matrix. The dimension column headers become the dimension names used in all downstream person-level output (ability and standard-error headers). An optional partial-credit column declares which items are scored in multiple levels, and optionally their maximum scores.

irtc_align_q compares the Q-matrix items with the response-data items. By default mismatches raise warnings (W420, W421) and the analysis continues with the shared items; on_mismatch = "error" turns any mismatch into an error (E422).

Usage

irtc_read_q(x, sheet = 1)

irtc_align_q(data, q, on_mismatch = c("warn", "error"))

## S3 method for class 'irtc_qmatrix'
print(x, lang = irtc_lang(), ...)

Arguments

x

A file path, data frame, or numeric matrix with item rownames. For the print method: an irtc_qmatrix object.

sheet

Excel sheet to read (number or name).

data

An irtc_data object (from irtc_read), data frame or matrix of item responses.

q

An irtc_qmatrix object, or anything accepted by irtc_read_q.

on_mismatch

"warn" (default): report item mismatches as warnings and continue with the shared items. "error": stop on any mismatch.

lang

Output language, "zh" or "en".

...

Ignored.

Details

Expected table layout for irtc_read_q:

Value

irtc_read_q returns an object of class irtc_qmatrix: a list with components Q (numeric item-by-dimension matrix with dimnames), partial (named logical vector), max_score (named integer vector, NA when not declared), log and source.

irtc_align_q returns a list with components data (the input data restricted to the shared items), q (the aligned irtc_qmatrix, rows in data column order), common, q_only and data_only (character vectors of item names).

See Also

irtc, irtc_read

Examples

qdf <- data.frame(item = c("I1", "I2", "I3"),
    algebra = c(1, 1, 0), geometry = c(0, 0, 1),
    partial = c(0, 1, 0))
qm <- irtc_read_q(qdf)
print(qm, lang = "en")

resp <- data.frame(I1 = c(0, 1), I2 = c(2, 0), I4 = c(1, 1))
al <- suppressWarnings(irtc_align_q(resp, qm))
al$q_only
al$data_only

Generate a Word or HTML Analysis Report

Description

Writes an analysis report with figures (Wright map, ability distribution, item quality summary, item characteristic curves) and tables. Three audience layouts are available: "decision" (a short executive summary with recommendations), "survey" (a plain-language full report) and "stat" (a complete technical report including item parameters, item fit and model information). Every layout includes a Model diagnostics section (convergence, information criteria with interpretation, EAP reliability band, item-fit reading) and a Data processing transparency section (weights summary, Q-matrix item alignment, unobserved-category collapses, dropped items, scoring summary, and - for "stat"/"survey" - the full cleaning log), detailed for statisticians and condensed for other audiences.

HTML reports are fully self-contained single files (images embedded); Word reports require the optional officer package.

Usage

irtc_report(mod, file, format = NULL,
    audience = c("survey", "decision", "stat"), lang = irtc_lang(),
    resp = NULL, title = NULL, overwrite = FALSE, verbose = TRUE)

Arguments

mod

A fitted irtc model object.

file

Output file path ending in .docx or .html.

format

"docx" or "html"; inferred from file when NULL.

audience

Report layout; see Description.

lang

Output language, "zh" or "en".

resp

The response data; only needed when the model object does not store it (streaming engine).

title

Report title; a bilingual default is used when NULL.

overwrite

Logical: overwrite an existing file?

verbose

Logical: print a completion message?

Value

Invisibly, the output file path.

See Also

irtc, plain_summary, irtc_excel, plot.irtc

Examples

set.seed(1)
theta <- rnorm(150)
resp <- as.data.frame(sapply(seq(-1, 1, length.out = 5), function(b) {
    as.numeric(runif(150) < plogis(theta - b))
}))
mod <- irtc(resp, model = "1PL", verbose = FALSE)

file <- tempfile(fileext = ".html")
irtc_report(mod, file, audience = "decision", lang = "en",
    verbose = FALSE)
file.exists(file)
unlink(file)

Machine-Readable Results with a Stable Schema

Description

Extracts fitted-model results as tidy data frames with a stable, documented schema aimed at automated callers (pipelines, AI agents). Column names are fixed English snake_case identifiers and never depend on the language option. irtc_json exports the same content as JSON (requires the optional jsonlite package).

Schema v1.1 components: model_info (one row: schema and package version, model, sizes, deviance, AIC/BIC, EAP reliability, iterations, and dimension_names when a Q matrix was supplied), items (per item: parameters, classical statistics, fit, quality rating and bilingual reasons/advice, plus a status column and, for polytomous items, semantic step difficulties and rare-category annotations), persons (per person: ID, number answered, raw score, EAP, SE, percentile, T score; ability/SE headers use the Q dimension names when available), cleaning_log and check_issues (present when the model was fitted via irtc). Schema 1.1 is additive over 1.0: existing column names and meanings are unchanged. Items declared in the Q matrix but not estimated keep a row with status "dropped_no_response" or "declared_not_estimated". See the package file inst/llms.txt for the full schema reference.

Usage

irtc_results(mod, resp = NULL)

irtc_json(mod, file = NULL, resp = NULL, pretty = TRUE)

## S3 method for class 'irtc_results'
print(x, lang = irtc_lang(), ...)

Arguments

mod

A fitted irtc model object; irtc_json also accepts an irtc_results object.

resp

The response data; only needed when the model object does not store it (streaming engine).

file

Optional path; when given, the JSON is written there (UTF-8) and the path is returned invisibly.

pretty

Logical: pretty-print the JSON?

x

An irtc_results object.

lang

Output language, "zh" or "en".

...

Ignored.

Value

irtc_results returns an object of class irtc_results, a list of data frames as described above. irtc_json returns a JSON string, or invisibly the file path when file is given.

See Also

irtc, irtc_excel

Examples

set.seed(1)
theta <- rnorm(150)
resp <- as.data.frame(sapply(seq(-1, 1, length.out = 5), function(b) {
    as.numeric(runif(150) < plogis(theta - b))
}))
mod <- irtc(resp, model = "1PL", verbose = FALSE)

res <- irtc_results(mod)
res$model_info
head(res$items)

if (requireNamespace("jsonlite", quietly = TRUE)) {
    json <- irtc_json(mod)
    substr(json, 1, 80)
}

Score Raw Responses with an Answer Key or Scoring Rules

Description

Converts raw multiple-choice responses (e.g. "A", "B", "C", "D") to 0/1 scores using an answer key, or maps responses to partial-credit scores through a rules table. Responses are normalised before matching: whitespace is trimmed, case is ignored and full-width characters are converted to half-width.

Both key and rules may also be file paths in any format supported by irtc_read. A key file needs an item column (item, "题目", ...) and an answer column (answer, "答案", ...); an optional partial-answer column (partial_answer, "部分正确答案", ...) lists answers worth partial credit, several separated by |, ;, , or "、". Items with partial answers are scored full = 2, partial = 1, other = 0; items without stay 0/1. For more than three score levels supply an explicit rules table instead.

Usage

irtc_score(resp, key = NULL, rules = NULL, na_as_wrong = FALSE,
    sheet = 1)

Arguments

resp

An irtc_data object (from irtc_read), a data frame or a matrix of raw responses.

key

A named vector mapping item names to correct answers, e.g. c(Q1 = "A", Q2 = "C"), or a path to a key file (see Description). An unnamed vector is matched to the item columns by position. Items not named in the key are left unchanged.

rules

A data frame with columns item, response, score defining partial-credit scoring, or a path to such a table (Chinese column aliases "题目", "作答" and "分值" are accepted). Observed responses without a rule are set to NA with a warning of class irtc_warning_scoring.

na_as_wrong

Logical: score missing responses as 0 instead of NA? (Key scoring only.)

sheet

Excel sheet of the key / rules file (number or name).

Value

The same type as the input: an irtc_data object with scored resp and an extended log, or a data frame with a "scoring_log" attribute.

See Also

irtc_read, irtc

Examples

resp <- data.frame(Q1 = c("A", "b", "C"), Q2 = c("c", "C", "D"),
    stringsAsFactors = FALSE)
irtc_score(resp, key = c(Q1 = "A", Q2 = "C"))

rules <- data.frame(item = "Q1", response = c("A", "B", "C"),
    score = c(2, 1, 0))
irtc_score(resp["Q1"], rules = rules)

Plain-Language Layered Summary of a Fitted Model

Description

Prints a layered, plain-language summary of a fitted item response model: conclusion first, then analysis overview, item quality, ability distribution and suggested next steps. Intended for survey staff and decision makers; statisticians can use summary(mod) for the full technical output.

Usage

plain_summary(mod, lang = irtc_lang())

Arguments

mod

A fitted irtc model object (from irtc, irtc.mml or irtc.mml.2pl).

lang

Output language, "zh" or "en".

Value

Invisibly, the list of summary sections (each with title and body); the same content that irtc_report uses.

See Also

irtc, irtc_report

Examples

set.seed(1)
theta <- rnorm(150)
resp <- as.data.frame(sapply(seq(-1, 1, length.out = 5), function(b) {
    as.numeric(runif(150) < plogis(theta - b))
}))
mod <- irtc(resp, model = "1PL", verbose = FALSE)
plain_summary(mod, lang = "en")

Diagnostic Plots for Fitted Item Response Models

Description

Base-graphics plots for a fitted model: "wright" (item difficulty vs person ability map), "ability" (person ability histogram, one panel per dimension), "quality" (item quality rating summary) and "icc" (item characteristic curves; unidimensional models only). The same figures are embedded in irtc_report reports.

Usage

## S3 method for class 'irtc'
plot(x, type = c("wright", "ability", "quality", "icc"),
    lang = irtc_lang(), items = NULL, resp = NULL, ...)

Arguments

x

A fitted irtc model object.

type

Plot type; see Description.

lang

Label language, "zh" or "en". Chinese labels require a CJK-capable graphics font.

items

For type = "icc": item indices or names to plot (default: the first 12 items).

resp

The response data; only needed when the model object does not store it (streaming engine).

...

Ignored.

Value

Invisibly, x.

See Also

irtc, irtc_report

Examples

set.seed(1)
theta <- rnorm(150)
resp <- as.data.frame(sapply(seq(-1, 1, length.out = 5), function(b) {
    as.numeric(runif(150) < plogis(theta - b))
}))
mod <- irtc(resp, model = "1PL", verbose = FALSE)
plot(mod, type = "wright", lang = "en")
plot(mod, type = "icc", lang = "en", items = 1:2)

These binaries (installable software) and packages are in development.
They may not be fully stable and should be used with caution. We make no claims about them.
Health stats visible at Monitor.