R API reference#
Use library(pyfcirt) to load the R interface. Create a model with
model() and call its methods with m$. Integers such as 42L supply
Python integer arguments. For installation and a complete fit, see the
R Quick start.
Prepare and fit#
model()
load_example(name, model, n_persons = NULL, random_seed = NULL, include_truth = FALSE)
m$add_fc(design, responses, format, model, response_format = "rank",
person_id_column = NULL, ...)
m$add_items(design, responses, format, model, kind = NULL,
categories = c(0L, 1L), person_id_column = NULL, ...)
m$set_population(group = NULL, reference_group = NULL, person_data = NULL, ...)
m$prepare(..., population = NULL)
m$set_priors(priors)
m$add_regressions(formulas, ...)
m$fit(..., var_names = NULL)
model()creates an empty analysis.load_example()returns a list withdesignandresponsesdata frames and the tableformat. It also supplies the FCresponse_formatandscaleor the itemcategories. Mixed examples put these fields underfcanditems.include_truth = TRUErequests generating parameters when available.Pass a design data frame or string, a response data frame and a model name to
add_fc()oradd_items(). For example,format = "comparison_long"uses the columnsperson_id,block_id,statement_1,statement_2andresponse. Setresponse_formatto"rank","pick","mole"orNULLfor direct comparisons. UsekindforDichotomousIRTvariants.prepare()validates and aligns the registered tables. Optional arguments includeperson_data = NULLandtheta_parameterization = "centered". For multiple groups, passpopulation = list(group = "school", reference_group = "A")and aperson_datatable withperson_idandschool. Includeregression_by_group = TRUEin the population list for group-specific slopes.set_priors()accepts a named list of native PyMC distributions.add_regressions()accepts a formula string and optional predictor tables such asperson_dataorstatement_data.fit()attaches posterior samples to the same model. Its forwarded defaults includedraws = 1000L,tune = 1000L,chains = NULL,target_accept = 0.8,nuts_sampler = "blackjax"andrandom_seed = NULL. Useretain_calibration = TRUEduring fitting if you plan to use posterior calibration for scoring. The configuration and fitting methods return the same model invisibly.
Differential item functioning#
DIF is experimental. Register the person table and population with
m$set_population() before m$prepare(). It accepts the same group, trait
scale, correlation and prior options as
Python’s population declaration.
With grouping, the reference group’s trait means and residual SDs are fixed
at zero and one. The focal groups’ means and covariance are free by default.
m$available_covariate_targets(level = NULL, kind = NULL)
m$add_dif_terms(targets, formula = NULL, ...)
m$dif_summary(contrasts = NULL, at = NULL, prob = 0.95, significant_only = FALSE)
targetsaccepts a character vector or a named list of target settings. Uselist(anchors = c("B01_1", "B01_2"))for statement IDs. For comparison cutpoints, supply anchors as a data frame withblock_id,statement_1andstatement_2. The model estimates one shared value per anchored parameter.formulais a right-hand-side string such as"site"or"site * language". Usereference_levels = list(site = "A", language = "en")to set categorical references. Supplyperson_dataif it was not registered before preparation andidif its ID column differs fromperson_id.priordefaults to"laplace". For example,prior_options = list(b = 0.2)sets its scale. Set named target options to give loading and cutpoint effects different priors. Pairwise L1 applies to categorical group terms. For truncated L1 on loadings, the default strength scales with respondent and group counts. Setprior_options = list(strength = 3)to use a fixed value. Formulas with numeric predictors use Laplace. Usegroups = list(c("site", "language"))for joint categorical profiles. See the DIF reference for prior options.available_covariate_targets(kind = "dif")anddif_summary()return R data frames. Indif_summary(),contrasts = list(site = c("A", "B"))reports B minus A. Useat = list(language = "en")to hold another predictor fixed. Use a two-element list of profile vectors for a joint-group comparison.probsets the equal-tailed interval probability, andsignificant_only = TRUEkeeps rows whose intervals exclude zero.
On a fresh prepared model, give different priors to loadings and cutpoints with one declaration:
m$add_dif_terms(
list(
"fc.loading_magnitude" = list(prior_options = list(b = 0.15)),
"fc.cutpoints" = list(prior = "pairwise_l1", prior_options = list(strength = 3))
),
formula = "site"
)
After fitting an interaction such as formula = "site * language", compare
sites at a fixed language:
m$dif_summary(contrasts = list(site = c("A", "B")), at = list(language = "en"))
See TIRT DIF in R for a complete example.
Inspect the data and posterior#
m$data_coverage(by = "model", details = FALSE)
m$response_data(blocks = NULL, items = NULL, representation = "auto", groups = NULL)
response_counts(answers, groupby = NULL)
summary(m, details = FALSE)
coef(m, blocks = NULL, items = NULL, component = "measurement",
ci_prob = 0.95, ci_kind = "hdi", var_names = NULL, coords = list(),
kind = "all", digits = 3L, ...)
m$trait_summary(by_group = FALSE, ci_prob = 0.95, ci_kind = "hdi", digits = 3L, ...)
as_draws(m, variables = NULL, coords = list(), chain = NULL, draw = NULL)
data_coverage()reports respondents, available responses and missingness. Useby = "block"orby = "item"for a breakdown by measurement unit.response_data()returns observed records. For additional grouping, pass a data frame with apersoncolumn and one column per group variable.response_counts()takes those records and returns counts, valid totals and proportions. Usegroupbyto add columns to the grouping.summary()returns a printable model description.coef()returns a data frame with parameter labels and posterior statistics. In mixed tests,channeldistinguishes FC blocks from individual items inunit. Group-specific estimates includepopulation_group. Setcomponent = "regression"for regression coefficients orci_kind = "eti"for equal-tailed intervals.digitscontrols printing.trait_summary()returns a named list of population trait summaries.as_draws()returns aposterior::draws_arraywith dimensions iteration × chain × variable.coordsaccepts dimension labels andblock,statement,pair,item, ortraitlabels. Use the pair text shown bycoef(), such as"S1 > S2". Multiple labels within one field are alternatives, while different fields are intersected. Shared parameters appear once. Variables without matching entries are omitted. A selection with no matching variable raises an error.chainanddrawselect original sample labels. Use thecoordinatesandsample_coordinatesattributes for the original labels. Variable names use the original dimension labels and stay stable across selections. Repeated labels in a selector raise an error. Integers outside R’s exact numeric range are stored asinteger:labels in coordinate metadata. Reuse those labels in selectors for the original integer coordinate.
For the 90-person calibration in the R Quick start:
m$data_coverage()$n_persons
# [1] 90
answers_B1 <- m$response_data(blocks = "B1")
counts_B1 <- response_counts(answers_B1)
sum(counts_B1$count) == nrow(answers_B1)
# [1] TRUE
loading <- as_draws(m, variables = "loading", chain = 0L, draw = 0L)
dim(loading)[1:2]
# [1] 1 1
as_draws(m, variables = "loading", coords = list(block = "B1", statement = "S1"))
as_draws(m, variables = "cutpoint", coords = list(block = "B1", pair = "S1 > S2"))
Predict, check and compare#
m$prior_predictive(...)
m$posterior_predictive(...)
predictive_view(predictions, block = NULL, item = NULL)
m$chi_ppp(blocks = NULL, items = NULL, ...)
plot_ppp(check, coords = list(), bins = 30L, quantile_range = NULL, max_panels = 12L)
m$residuals(...)
m$log_likelihood(...)
waic(log_likelihood)
dic(log_likelihood)
m$information(..., draw = NULL)
m$reliability(method = "ratio", person_ids = NULL)
Predictive methods return xarray trees. Prior prediction defaults to
draws = 500Landsave_responses = FALSE. Posterior prediction uses all posterior states whendraws = NULLand includes probabilities wheninclude_probabilities = TRUE. Both default torandom_seed = NULLandstore = TRUE.Select exactly one
blockoriteminpredictive_view(). The R list contains observed responsesy, a matrix with one predictive draw per row and one observation per column inyrep, supporting response categories, and observation and sample coordinates.chi_ppp()returns an R list withsummaryand labelled discrepancy draws. It acceptspredictions = NULL,groupby = "overall",draws = NULL,random_seed = NULL,save_discrepancy = FALSE,store = TRUEandprogressbar = TRUE. Pass the result toplot_ppp()for an editable ggplot.residuals()returns a labelled xarray dataset.log_likelihood()returns a labelled chain × draw × observation array. Both default toprogressbar = TRUE, and log likelihood defaults tostore = TRUE. Pass that array towaic()ordic()for named R lists of comparison statistics.information()returns labelled expected Fisher information. By default it uses the fitted posterior parameter point, withparameters = NULL,theta = NULL,include_intermediates = FALSE,store = TRUEandprogressbar = TRUE. Setdraw = c(chain, draw)to select a single state by its original labels.reliability()returns a data frame by trait.
Score, simulate and restore#
m$score(new_responses, ..., format = NULL, var_names = NULL)
m$score_model(new_responses, ..., format = NULL)
m$simulate(..., draw = NULL)
save_results(m, path)
m$attach_samples(samples, assume_same_batch = FALSE)
Pass a new response data frame and its
formattoscore(). It returns a fitted R model for the new respondents. For a mixed test, usenew_responses = list(fc = fc_answers, items = item_answers)andformat = c(fc = "comparison_long", items = "item_long"). Passperson_datawith the trained group and predictor columns. Scoring reuses the calibration’s group labels and fitted formula encoding. Both scoring methods default tocalibration = "point", which fixes the calibration parameters. Usecalibration = "posterior"for experimental scoring with calibration uncertainty.score_model()prepares the new model for a separate estimation step.score()also accepts the fitting options.simulate()returns a separate unfitted model with simulated responses. It defaults tosource = "prior". Usesource = "posterior"to simulate from a fitted model, orsource = "fixed"with explicitparameters.save_results()writes NetCDF and invisibly returns the path. To restore, prepare a matching model and pass the file path to itsattach_samples()method. The method also accepts a native result tree.
Mixed FC and ordinal scoring#
For a test with FC blocks and Likert items, register the two channels on the
same model. Supply the calibration people with person_id, school and
age, and use the same columns for new respondents.
m <- model()
m$add_fc(fc_design, fc_answers, format = "comparison_long", model = "TIRT")
m$add_items(item_design, item_answers, format = "item_long", model = "GPCM",
categories = 0:2)
m$prepare(person_data = calibration_people,
population = list(group = "school", reference_group = "A",
regression_by_group = TRUE))
m$add_regressions("theta ~ age", person_data = calibration_people)
m$fit(random_seed = 42L)
coef(m, blocks = "B1", items = "I1", kind = "stats")
coef(m, component = "regression", kind = "stats")
scored <- m$score(list(fc = new_fc, items = new_items),
format = c(fc = "comparison_long", items = "item_long"),
person_data = new_people, random_seed = 43L)
The mixed response types example shows a fitted model and its coefficient table.
The TIRT in R example uses the same calibration for
model checking, scoring and restoring saved draws. Python options passed through
... follow the Python API reference.