Movatterモバイル変換


[0]ホーム

URL:


Version:1.5.3
Date:2025-09-23
Title:Hierarchical Multinomial Processing Tree Modeling
Maintainer:Daniel W. Heck <daniel.heck@uni-marburg.de>
Depends:R (≥ 4.0.0)
Imports:Rcpp (≥ 1.0.0), stats, parallel, graphics, utils, grDevices,MASS, runjags, rjags, coda, hypergeo, logspline
Suggests:knitr, rmarkdown, testthat, R.rsp
LinkingTo:Rcpp, RcppArmadillo
VignetteBuilder:knitr, R.rsp
NeedsCompilation:yes
SystemRequirements:JAGS (https://mcmc-jags.sourceforge.io/)
Description:User-friendly analysis of hierarchical multinomial processing tree (MPT) models that are often used in cognitive psychology. Implements the latent-trait MPT approach (Klauer, 2010) <doi:10.1007/s11336-009-9141-0> and the beta-MPT approach (Smith & Batchelder, 2010) <doi:10.1016/j.jmp.2009.06.007> to model heterogeneity of participants. MPT models are conveniently specified by an .eqn-file as used by other MPT software and data are provided by a .csv-file or directly in R. Models are either fitted by calling JAGS or by an MPT-tailored Gibbs sampler in C++ (only for nonhierarchical and beta MPT models). Provides tests of heterogeneity and MPT-tailored summaries and plotting functions. A detailed documentation is available in Heck, Arnold, & Arnold (2018) <doi:10.3758/s13428-017-0869-7> and a tutorial on MPT modeling can be found in Schmidt, Erdfelder, & Heck (2023) <doi:10.1037/met0000561>.
License:GPL-3
Encoding:UTF-8
URL:https://github.com/danheck/TreeBUGS
RoxygenNote:7.3.3
LazyData:TRUE
Packaged:2025-09-23 12:57:40 UTC; Daniel
Author:Daniel W. HeckORCID iD [aut, cre], Nina R. Arnold [aut, dtc], Denis Arnold [aut], Alexander Ly [ctb], Marius BarthORCID iD [ctb]
Repository:CRAN
Date/Publication:2025-09-23 13:30:02 UTC

TreeBUGS: Hierarchical Multinomial Processing Tree Modeling

Description

logo

Uses standard MPT files in the .eqn-format (Moshagen, 2010) to fithierarchical Bayesian MPT models. Note that the software JAGS is required(https://mcmc-jags.sourceforge.io/).

The core functions either fit a Beta-MPT model (betaMPT; Smith& Batchelder, 2010) or a latent-trait MPT model (traitMPT;Klauer, 2010). A fitted model can be inspected using convenient summary andplot functions tailored to hierarchical MPT models.

Detailed explanations and examples can be found in the package vignette,accessible viavignette("TreeBUGS")

Citation

If you use TreeBUGS, please cite the software as follows:

Heck, D. W., Arnold, N. R., & Arnold, D. (2018).TreeBUGS: An R package for hierarchical multinomial-processing-tree modeling.Behavior Research Methods, 50, 264–284.doi:10.3758/s13428-017-0869-7

Tutorial

For a tutorial on MPT modeling (including hierarchical modeling in TreeBUGS), see:

Schmidt, O., Erdfelder, E., & Heck, D. W. (2023).How to develop, test, and extend multinomial processing tree models: A tutorial.Psychological Methods.doi:10.1037/met0000561.(Preprint:https://osf.io/preprints/psyarxiv/gh8md/)

Author(s)

Daniel W. Heck, Denis Arnold, & Nina Arnold

References

Klauer, K. C. (2010). Hierarchical multinomial processing tree models:A latent-trait approach.Psychometrika, 75, 70-98.doi:10.1007/s11336-009-9141-0

Matzke, D., Dolan, C. V., Batchelder, W. H., & Wagenmakers, E.-J. (2015).Bayesian estimation of multinomial processing tree models with heterogeneityin participants and items.Psychometrika, 80, 205-235.doi:10.1007/s11336-013-9374-9

Moshagen, M. (2010).multiTree: A computer program for the analysis of multinomial processingtree models.Behavior Research Methods, 42, 42-54.doi:10.3758/BRM.42.1.42

Smith, J. B., & Batchelder, W. H. (2008).Assessing individual differences in categorical data.Psychonomic Bulletin & Review, 15, 713-731.doi:10.3758/PBR.15.4.713

Smith, J. B., & Batchelder, W. H. (2010).Beta-MPT: Multinomial processing tree models for addressingindividual differences.Journal of Mathematical Psychology, 54, 167-183.doi:10.1016/j.jmp.2009.06.007

See Also

Useful links:


Bayes Factors for Simple (Nonhierarchical) MPT Models

Description

Computes Bayes factors for simple (fixed-effects, nonhierarchical) MPT modelswith beta distributions as priors on the parameters.

Usage

BayesFactorMPT(  models,  dataset = 1,  resample,  batches = 5,  scale = 1,  store = FALSE,  cores = 1)

Arguments

models

list of models fitted withsimpleMPT, e.g.,list(mod1, mod2)

dataset

for which data set should Bayes factors be computed?

resample

how many of the posterior samples of the MPT parametersshould be resampled per model

batches

number of batches. Used to compute a standard error of theestimate.

scale

how much should posterior-beta approximations be downscaled toget fatter importance-sampling density

store

whether to save parameter samples

cores

number of CPUs used

Details

Currently, this is only implemented for a single data set!

Uses a Rao-Blackwellized version of the product-space method (Carlin & Chib,1995) as proposed by Barker and Link (2013). First, posterior distributionsof the MPT parameters are approximated by independent beta distributions.Second, for one a selected model, parameters are sampled from these proposaldistributions. Third, the conditional probabilities to switch to a differentmodel are computed and stored. Finally, the eigenvector with eigenvalue oneof the matrix of switching probabilities provides an estimate of theposterior model probabilities.

References

Barker, R. J., & Link, W. A. (2013). Bayesian multimodelinference by RJMCMC: A Gibbs sampling approach. The American Statistician,67(3), 150-156.

Carlin, B. P., & Chib, S. (1995). Bayesian model choice via Markov chainMonte Carlo methods. Journal of the Royal Statistical Society. Series B(Methodological), 57(3), 473-484.

See Also

marginalMPT


Bayes Factor for Slope Parameters in Latent-Trait MPT

Description

Uses the Savage-Dickey method to compute the Bayes factor that the slopeparameter of a continuous covariate intraitMPT is zero vs.positive/negative/unequal to zero.

Usage

BayesFactorSlope(  fittedModel,  parameter,  direction = "!=",  approx = "normal",  plot = TRUE,  ...)

Arguments

fittedModel

a fitted latent-trait model fitted withtraitMPT with predictor variables that have been defined viapredStructure.

parameter

name of the slope parameter (e.g.,"slope_d_covariate").

direction

alternative hypothesis: whether slope is smaller or largerthan zero ("<" or">") or unequal to zero ("!=").

approx

how to approximate the posterior density of the slope parameterat zero:approx="normal" uses a normal approximation to all samplesandapprox="logspline" uses a nonparametric density estimate of thepackagelogspline. Usually, both methods provide similarresults.

plot

ifTRUE, the prior and posterior densities and the ratioat slope=0 are plotted.

...

further arguments passed tologspline,which is used to approximate the density of the posterior distribution.

Details

The Bayes factor is computed with the Savage-Dickey method, which isdefined as the ratio of the density of the posterior and the density of theprior evaluated atslope=0 (Heck, 2019). Note that this method cannotbe used with default JZS priors (IVprec="dgamma(.5,.5)") if more thanone predictor is added for an MPT parameter. As a remedy, a g-prior (normaldistribution) can be used on the slopes by setting the hyperprior parameterg to a fixed constant when fitting the model:traitMPT(...,IVprec = 1) (see Heck, 2019).

References

Heck, D. W. (2019). A caveat on the Savage-Dickey density ratio:The case of computing Bayes factors for regression parameters.BritishJournal of Mathematical and Statistical Psychology, 72, 316–333.doi:10.1111/bmsp.12150

Examples

## Not run: # latent-trait MPT model for the encoding condition (see ?arnold2013):EQNfile <- system.file("MPTmodels/2htsm.eqn", package = "TreeBUGS")d.enc <- subset(arnold2013, group == "encoding")fit <- traitMPT(EQNfile,  data = d.enc[, -(1:4)], n.thin = 5,  restrictions = list("D1=D2=D3", "d1=d2", "a=g"),  covData = d.enc[, c("age", "pc")],  predStructure = list("D1 ; age"))plot(fit, parameter = "slope", type = "default")summary(fit)BayesFactorSlope(fit, "slope_D1_age", direction = "<")## End(Not run)

Compute Posterior Predictive P-Values

Description

Computes posterior predictive p-values to test model fit.

Usage

PPP(fittedModel, M = 1000, nCPU = 4, T2 = TRUE, type = "X2")

Arguments

fittedModel

fitted latent-trait or beta MPT model (traitMPT,betaMPT)

M

number of posterior predictive samples. As a maximum, the number of posterior samples infittedModel is used.

nCPU

number of CPUs used for parallel sampling. For large models and many participants, this requires considerable computer-memory resources (as a remedy, usenCPU=1).

T2

whether to compute T2 statistic to check coveriance structure (cantake a lot of time). If some participants do not have responses for sometrees, (co)variances are computed by pairwise deletion of the correspondingpersons.

type

whether the T1 statistic of expected means is computed usingPerson's"X2" or the likelihood-ratio statistic"G2"

Author(s)

Daniel Heck

References

Klauer, K. C. (2010). Hierarchical multinomial processing treemodels: A latent-trait approach. Psychometrika, 75, 70-98.


WAIC: Widely Applicable Information Criterion

Description

Implementation of the WAIC for model comparison.

Usage

WAIC(  fittedModel,  n.adapt = 1000,  n.chains = 3,  n.iter = 10000,  n.thin = 1,  summarize = FALSE)## S3 method for class 'waic'print(x, ...)## S3 method for class 'waic_difference'print(x, ...)## S3 method for class 'waic'e1 - e2

Arguments

fittedModel

fitted latent-trait or beta MPT model (traitMPT,betaMPT)

n.adapt

number of adaptation samples.

n.chains

number of chains (no parallel computation).

n.iter

number of iterations after burnin.

n.thin

Thinning rate.

summarize

deprecated argument only available for backwards compatibility

x

An object of classwaic orwaic_difference to be printed.

...

Further arguments that may be passed to print methods.

e1,e2

Two objects of classwaic to be compared.

Details

WAIC provides an approximation of predictive accuracy with respectto out-of-sample deviance. The uncertainty of the WAIC for the given numberof observed nodes (i.e., number of free categories times the number ofparticipants) is quantified by the standard error of WAIC"se_waic"(cf. Vehtari et al., 2017). In contrast, to assess whether the approximationuncertainty due to MCMC sampling (not sample size) is sufficiently low, it isa good idea to fit each model twice and compute WAIC again to assess thestability of the WAIC values.

For more details, see Vehtari et al. (2017) and the following discussionabout the JAGS implementation (which is currently an experimental feature ofJAGS 4.3.0):

https://sourceforge.net/p/mcmc-jags/discussion/610036/thread/8211df61/

Value

FunctionWAIC() returns an object of classwaic, which is basicallya list containing three vectorsp_waic,deviance, andwaic, withseparate values for each observed node(i.e., for all combinations of persons and free categories).

For these objects, aprint() method exists, whichalso calculates the standard error of the estimate of WAIC.

For backwards compatibility, ifWAIC() is called withsummarize = TRUE,a vector with valuesp_waic,deviance,waic, andse_waic is returned.

WAIC values from two models can be compared by using the- operator;the result is an object of classwaic_difference.

References

Vehtari, A., Gelman, A., & Gabry, J. (2017). Practical Bayesianmodel evaluation using leave-one-out cross-validation and WAIC. Statisticsand Computing, 27(5), 1413–1432. doi:10.1007/s11222-016-9696-4

Examples

## Not run: #### WAIC for a latent-trait MPT model:fit <- traitMPT(...)WAIC(fit)#### pairwise comparison of two models:# (1) compute WAIC per modelwaic1 <- WAIC(fit1)waic2 <- WAIC(fit2)# (2) WAIC differencewaic1 - waic2## End(Not run)

Data of a Source-Monitoring Experiment

Description

Dataset of a source-monitoring experiment by Arnold, Bayen, Kuhlmann, andVaterrodt (2013) using a 2 (Source; within) x 3 (Expectancy; within) x 2(Time of Schema Activation; between) mixed factorial design.

Usage

arnold2013

Format

A data frame 13 variables:

subject

Participant code

age

Age in years

group

Between-subject factor "Time of Schema Activation":Retrieval vs. encoding condition

pc

perceived contingency

EE

Frequency of "Source E" responses to items from source "E"

EU

Frequency of "Source U" responses to items from source "E"

EN

Frequency of "New" responses to items from source "E"

UE

Frequency of "Source E" responses to items from source "E"

UU

Frequency of "Source U" responses to items from source "E"

UN

Frequency of "New" responses to items from source "E"

NE

Frequency of "Source E" responses to new items

NU

Frequency of "Source U" responses to new items

NN

Frequency of "New" responses to new items

Details

Eighty-four participants had to learn statements that were eitherpresented by a doctor or a lawyer (Source) and were either typical fordoctors, typical for lawyers, or neutral (Expectancy). These two types ofstatements were completely crossed in a balanced way, resulting in a truecontingency of zero between Source and Expectancy. Whereas the professionschemata were activated at the time of encoding for half of the participants(encoding condition), the other half were told about the profession of thesources just before the test (retrieval condition). After the test,participants were asked to judge the contingency between item type and source(perceived contingency pc).

References

Arnold, N. R., Bayen, U. J., Kuhlmann, B. G., & Vaterrodt, B.(2013). Hierarchical modeling of contingency-based source monitoring: Atest of the probability-matching account. Psychonomic Bulletin & Review,20, 326-333.

Examples

head(arnold2013)## Not run: # fit hierarchical MPT model for encoding condition:EQNfile <- system.file("MPTmodels/2htsm.eqn", package = "TreeBUGS")d.encoding <- subset(arnold2013, group == "encoding", select = -(1:4))fit <- betaMPTcpp(EQNfile, d.encoding,  n.thin = 5,  restrictions = list("D1=D2=D3", "d1=d2", "a=g"))# convergenceplot(fit, parameter = "mean", type = "default")summary(fit)## End(Not run)

Fit a Hierarchical Beta-MPT Model

Description

Fits a Beta-MPT model (Smith & Batchelder, 2010) based on a standard MPTmodel file (.eqn) and individual data table (.csv).

Usage

betaMPT(  eqnfile,  data,  restrictions,  covData,  transformedParameters,  corProbit = FALSE,  alpha = "dgamma(1, 0.1)T(1,)",  beta = "dgamma(1, 0.1)T(1,)",  n.iter = 20000,  n.adapt = 2000,  n.burnin = 2000,  n.thin = 5,  n.chains = 3,  dic = FALSE,  ppp = 0,  monitorIndividual = TRUE,  modelfilename,  parEstFile,  posteriorFile,  autojags = NULL,  ...)

Arguments

eqnfile

The (relative or full) path to the file that specifies the MPTmodel (standard .eqn syntax). Note that category labels must start with aletter (different to multiTree) and match the column names ofdata.Alternatively, the EQN-equations can be provided within R as a charactervalue (cf.readEQN). Note that the first line of an .eqn-fileis reserved for comments and always ignored.

data

The (relative or full) path to the .csv file with the data (commaseparated; category labels in first row). Alternatively: a data frame ormatrix (rows=individuals, columns = individual category frequencies,category labels as column names)

restrictions

Specifies which parameters should be (a) constant (e.g.,"a=b=.5") or (b) constrained to be identical (e.g.,"Do=Dn")or (c) treated as fixed effects (i.e., identical for all participants;"a=b=FE"). Either given as the path to a text file with restrictionsper row or as a list of restrictions, e.g.,list("D1=D2","g=0.5").Note that numbers in .eqn-equations (e.g.,d*(1-g)*.50) are directlyinterpreted as equality constraints.

covData

Data that contains covariates, for which correlations withindividual MPT parameters will be sampled. Either the path to a .csv file(comma-separated: rows=individuals in the same order asdata; firstrow must contain covariate labels). Alternatively: a data frame or matrix(rows=individuals, columns = variables; covariate labels as column names).Note that inbetaMPT, correlations are computed for discretevariables that are coded numerically (intraitMPT, this can besuppressed by usingpredType="f")

transformedParameters

list with parameter transformations that shouldbe computed based on the posterior samples of the group-level means (e.g.,for testing parameter differences:list("diffD=Do-Dn")), or path toa text file containing one transformation per line. Transformations ofindividual-level parameters can also be performed after fitting a modelusingtransformedParameters.

corProbit

whether to use probit-transformed MPT parameters to computecorrelations (probit-values of+Inf are truncated tomax(5,max(probit)); similarly for-Inf). Default forbeta-MPT: MPT parameters are used on the probability scale [0,1].

alpha

Hyperprior for the shape parameters\alpha of thegroup-level beta distributions (in JAGS syntax). Default: Truncated gammadistributions for\alpha and\beta with shape 1 and rate 0.1and truncated to be larger than 1 (seeplotPrior). A named vectorcan be used to specify separate hyperpriors for each MPT parameter (ifunnamed, the order of parameters is determined by the default order asshown byreadEQN withparamOrder = TRUE). Originally,Smith and Batchelder (2008) used the "WinBUGS-zeros-trick" (available inTreeBUGS ifalpha="zero" orbeta="zero"), which approximatesuniform priors on the group-level mean and SD (but often resultsconvergence issues).

beta

Hyperprior for\beta of group-level distributions, seealpha.

n.iter

Number of iterations per chain (including burnin samples). Seerun.jags for details.

n.adapt

number of adaption samples to adjust MCMC sampler in JAGS. Thesampler will be more efficient if it is tuned well. However, MCMC samplingwill still give correct results even if the warning appears: "Adaptationincomplete." (this just means that sampling efficiency could be better).

n.burnin

Number of samples for burnin (samples will not be stored andremoved from n.iter)

n.thin

Thinning rate.

n.chains

number of MCMC chains (sampled in parallel, which can bechanged via the additional argumentn.sim = 1).

dic

whether to compute DIC usingextract.runjags, which requires additional sampling.Can also be computed and added after fitting the model byfittedModel$summary$dic <- runjags::extract(fittedModel$runjags,"dic"). As an alternative information criterion,WAIC can becomputed for fitted models.

ppp

number of samples to compute posterior predictive p-value (seeposteriorPredictive)

monitorIndividual

whether to store MCMC samples of the MPTparameterstheta at the individual level (i.e., the random effects).IfFALSE, it is not possible to perform posterior-predictive checks.

modelfilename

name of the generated JAGS model file. Default is towrite this information to the tempdir as required by CRAN standards.

parEstFile

Name of the file to with the estimates should be stored(e.g., "parEstFile.txt")

posteriorFile

path to RData-file where to save the model includingMCMC posterior samples (an object namedfittedModel; e.g.,posteriorFile="mcmc.RData")

autojags

JAGS first fits the MPT model as usual and then draws MCMCsamples repeatedly until convergence. For this, the functionautoextend.jags is used with the arguments provided inautojags (this can be an empty list, in which case the defaults areused). Possible arguments forautoextend.jags are:list(startburnin = 1000, startsample = 5000, adapt = 2000,max.time="30m") (the last of these arguments restricts sampling to 30minutes, seeautoextend.jags).

...

further arguments passed to the JAGS sampling functionrun.jags. The number of CPUs/cores forthe"parallel" method can be changed via the argumentn.sim = 1.It is also possible to provide an existingparallel cluster objectvia the argumentcl. Reproducible results can beobtained by setting a random seed before fitting a model (i.e.,set.seed(12345) ).

Details

Note that, in the Beta-MPT model, correlations of individual MPTparameters with covariates are sampled. Hence, the covariates do not affectthe estimation of the actual Beta-MPT parameters. Therefore, the correlationof covariates with the individual MPT parameters can equivalently beperformed after fitting the model using the sampled posterior parametervalues stored inbetaMPT$mcmc

Value

a list of the classbetaMPT with the objects:

Author(s)

Daniel W. Heck, Nina R. Arnold, Denis Arnold

References

Heck, D. W., Arnold, N. R., & Arnold, D. (2018). TreeBUGS: An Rpackage for hierarchical multinomial-processing-tree modeling.BehaviorResearch Methods, 50, 264–284.doi:10.3758/s13428-017-0869-7

Smith, J. B., & Batchelder, W. H. (2010). Beta-MPT: Multinomial processingtree models for addressing individual differences.Journal ofMathematical Psychology, 54, 167-183.doi:10.1016/j.jmp.2009.06.007

Examples

## Not run: # fit beta-MPT model for encoding condition (see ?arnold2013):EQNfile <- system.file("MPTmodels/2htsm.eqn", package = "TreeBUGS")d.encoding <- subset(arnold2013, group == "encoding", select = -(1:4))fit <- betaMPT(EQNfile, d.encoding,  n.thin = 5,  restrictions = list("D1=D2=D3", "d1=d2", "a=g"))# convergenceplot(fit, parameter = "mean", type = "default")summary(fit)## End(Not run)

C++ Sampler for Hierarchical Beta-MPT Model

Description

Fast Gibbs sampler in C++ that is tailored to the beta-MPT model.

Usage

betaMPTcpp(  eqnfile,  data,  restrictions,  covData,  corProbit = FALSE,  n.iter = 20000,  n.burnin = 2000,  n.thin = 5,  n.chains = 3,  ppp = 0,  shape = 1,  rate = 0.1,  parEstFile,  posteriorFile,  cores = 1)

Arguments

eqnfile

The (relative or full) path to the file that specifies the MPTmodel (standard .eqn syntax). Note that category labels must start with aletter (different to multiTree) and match the column names ofdata.Alternatively, the EQN-equations can be provided within R as a charactervalue (cf.readEQN). Note that the first line of an .eqn-fileis reserved for comments and always ignored.

data

The (relative or full) path to the .csv file with the data (commaseparated; category labels in first row). Alternatively: a data frame ormatrix (rows=individuals, columns = individual category frequencies,category labels as column names)

restrictions

Specifies which parameters should be (a) constant (e.g.,"a=b=.5") or (b) constrained to be identical (e.g.,"Do=Dn")or (c) treated as fixed effects (i.e., identical for all participants;"a=b=FE"). Either given as the path to a text file with restrictionsper row or as a list of restrictions, e.g.,list("D1=D2","g=0.5").Note that numbers in .eqn-equations (e.g.,d*(1-g)*.50) are directlyinterpreted as equality constraints.

covData

Data that contains covariates, for which correlations withindividual MPT parameters will be sampled. Either the path to a .csv file(comma-separated: rows=individuals in the same order asdata; firstrow must contain covariate labels). Alternatively: a data frame or matrix(rows=individuals, columns = variables; covariate labels as column names).Note that inbetaMPT, correlations are computed for discretevariables that are coded numerically (intraitMPT, this can besuppressed by usingpredType="f")

corProbit

whether to use probit-transformed MPT parameters to computecorrelations (probit-values of+Inf are truncated tomax(5,max(probit)); similarly for-Inf). Default forbeta-MPT: MPT parameters are used on the probability scale [0,1].

n.iter

Number of iterations per chain (including burnin samples). Seerun.jags for details.

n.burnin

Number of samples for burnin (samples will not be stored andremoved from n.iter)

n.thin

Thinning rate.

n.chains

number of MCMC chains (sampled in parallel, which can bechanged via the additional argumentn.sim = 1).

ppp

number of samples to compute posterior predictive p-value (seeposteriorPredictive)

shape

shape parameter(s) of Gamma-hyperdistribution for thehierarchical beta-parameters\alpha_s and\beta_s (can be anamed vector to provide different hyperpriors for each parameter)

rate

rate parameter(s) of Gamma-hyperdistribution

parEstFile

Name of the file to with the estimates should be stored(e.g., "parEstFile.txt")

posteriorFile

path to RData-file where to save the model includingMCMC posterior samples (an object namedfittedModel; e.g.,posteriorFile="mcmc.RData")

cores

number of CPUs to be used

Author(s)

Daniel Heck

Examples

## Not run: # fit beta-MPT model for encoding condition (see ?arnold2013):EQNfile <- system.file("MPTmodels/2htsm.eqn", package = "TreeBUGS")d.encoding <- subset(arnold2013, group == "encoding", select = -(1:4))fit <- betaMPTcpp(EQNfile, d.encoding,  n.thin = 5,  restrictions = list("D1=D2=D3", "d1=d2", "a=g"))# convergenceplot(fit, parameter = "mean", type = "default")summary(fit)## End(Not run)

Between-Subject Comparison of Parameters

Description

Computes differencesor other statistics of MPT parameters for twohierarchical MPT models fitted separately to between-subjects data

Usage

betweenSubjectMPT(  model1,  model2,  par1,  par2 = par1,  stat = c("x-y", "x<y"),  plot = FALSE)

Arguments

model1

fitted hierarchical MPT model for first between-subjectscondition

model2

fitted hierarchical MPT model for second between-subjectscondition

par1

label of parameter from first model for which statistic should becomputed

par2

label of parameter from second model. Default: The same parameteras in the first model

stat

one or more functions of the parameters using"x" and"y" as placeholders for the parameters from the first and secondmodel, respectively. Default: Compute (A) the difference between parametersand (B) a Bayesian p-value (by counting how often x<y).

plot

whether to plot the convergence of the difference in parameters

Value

a list of the classbetweenMPT with the values:

Author(s)

Daniel Heck


Posterior Distribution for Correlations

Description

Adjusts the posterior distribution of correlations for the sampling error ofa population correlation according to the sample size (i.e., the number ofparticipants; Ly, Marsman, & Wagenmakers, 2018).

Usage

correlationPosterior(  fittedModel,  r,  N,  kappa = 1,  ci = 0.95,  M = 1000,  precision = 0.005,  maxiter = 10000,  plot = TRUE,  nCPU = 4)

Arguments

fittedModel

a fittedbetaMPT ortraitMPT model withcovariates (added during fitting by the argumentcovData)

r

optional: a vector of posterior correlations (instead offittedModel)

N

only ifr is used: the number of participants the correlationis based on

kappa

parameter for the prior of the correlation, that is, a scaledbeta distribution: Beta(1/kappa, 1/kappa). The defaultkappa=1defines a uniform distribution on [-1,1], whereaskappa<1 defines aunimodal prior centered around zero.

ci

credibility interval

M

number of subsamples from the fitted model

precision

precision on the interval [-1,1] to approximate theposterior density

maxiter

maximum number of iterations ingenhypergeo. Higher values might be necessary toincrease numerical stability for large correlations (r>.95).

plot

whether to plot (a) the unadjusted posterior correlations (grayhistogram) and (b) the corrected posterior (black line with red credibilityintervals)

nCPU

number of CPUs used for parallel computation of posteriordistribution

Details

This function (1) uses all posterior samples of a correlation to (2)derive the posterior of the correlation corrected for sampling error and (3)averages these densities across the posterior samples. Thereby, the methodaccounts for estimation uncertainty of the MPT model (due to the use of theposterior samples) and also for sampling error of the population correlationdue to sample size (cf. Ly, Boehm, Heathcote, Turner, Forstmann, Marsman, &Matzke, 2016).

Author(s)

Daniel W. Heck, Alexander Ly

References

Ly, A., Marsman, M., & Wagenmakers, E.-J. (2018). Analyticposteriors for Pearson’s correlation coefficient.StatisticaNeerlandica, 72, 4–13.doi:10.1111/stan.12111

Ly, A., Boehm, U., Heathcote, A., Turner, B. M. , Forstmann, B., Marsman,M., and Matzke, D. (2017). A flexible and efficient hierarchical Bayesianapproach to the exploration of individual differences incognitive-model-based neuroscience.https://osf.io/evsyv/.doi:10.1002/9781119159193

Examples

# test effect of number of participants:set.seed(123)cors <- rbeta(50, 100, 70)correlationPosterior(r = cors, N = 10, nCPU = 1)correlationPosterior(r = cors, N = 100, nCPU = 1)

Extend MCMC Sampling for MPT Model

Description

Adds more MCMC samples to the fitted MPT model.

Usage

extendMPT(fittedModel, n.iter = 10000, n.adapt = 1000, n.burnin = 0, ...)

Arguments

fittedModel

a fittedtraitMPT orbetaMPT

n.iter

Number of iterations per chain (including burnin samples). Seerun.jags for details.

n.adapt

number of adaption samples to adjust MCMC sampler in JAGS. Thesampler will be more efficient if it is tuned well. However, MCMC samplingwill still give correct results even if the warning appears: "Adaptationincomplete." (this just means that sampling efficiency could be better).

n.burnin

Number of samples for burnin (samples will not be stored andremoved from n.iter)

...

further arguments passed toextend.jags (see argumentslisted in:run.jags).

When drawing more samples, JAGS requires an additional adaptation phase, inwhich the MCMC sampling procedure is adjusted. Note that the MCMC samplingwill still give correct results even if the warning appears: "Adaptationincomplete." (this just means that sampling efficiency is not optimal).


Generate Data for Beta MPT Models

Description

Generating a data file with known parameter structure using the Beta-MPT.Useful for simulations and robustness checks.

Usage

genBetaMPT(  N,  numItems,  eqnfile,  restrictions,  mean = NULL,  sd = NULL,  alpha = NULL,  beta = NULL,  warning = TRUE)

Arguments

N

number of participants

numItems

number of responses per tree (a named vector with treelabels)

eqnfile

The (relative or full) path to the file that specifies the MPTmodel (standard .eqn syntax). Note that category labels must start with aletter (different to multiTree) and match the column names ofdata.Alternatively, the EQN-equations can be provided within R as a charactervalue (cf.readEQN). Note that the first line of an .eqn-fileis reserved for comments and always ignored.

restrictions

Specifies which parameters should be (a) constant (e.g.,"a=b=.5") or (b) constrained to be identical (e.g.,"Do=Dn")or (c) treated as fixed effects (i.e., identical for all participants;"a=b=FE"). Either given as the path to a text file with restrictionsper row or as a list of restrictions, e.g.,list("D1=D2","g=0.5").Note that numbers in .eqn-equations (e.g.,d*(1-g)*.50) are directlyinterpreted as equality constraints.

mean

Named vector of true group means of individual MPT parameters. Ifthe vector is not named, the internal order of parameters is used (can beobtained usingreadEQN).

sd

named vector of group standard deviations of individual MPTparameters.

alpha

Alternative specification of the group-level distribution usingthe shape parameters of the beta distribution (seedbeta).

beta

seealpha

warning

whether to show warning in case the naming of data-generatingparameters are unnamed or do not match

Details

Data are generated in a two-step procedure. First, person parametersare sampled from the specified beta distributions for each paramter (eitherbased on mean/sd or based on alpha/beta). In a second step, responsefrequencies are sampled for each person usinggenMPT.

Value

a list including the generated frequencies (data) and thetrue, underlying parameters (parameters) on the group and individuallevel.

References

Smith, J. B., & Batchelder, W. H. (2010). Beta-MPT: Multinomialprocessing tree models for addressing individual differences. Journal ofMathematical Psychology, 54, 167-183.

See Also

genMPT

Examples

# Example: Standard Two-High-Threshold Model (2HTM)EQNfile <- system.file("MPTmodels/2htm.eqn", package = "TreeBUGS")genDat <- genBetaMPT(  N = 100,  numItems = c(Target = 250, Lure = 250),  eqnfile = EQNfile,  mean = c(Do = .7, Dn = .5, g = .5),  sd = c(Do = .1, Dn = .1, g = .05))head(genDat$data, 3)plotFreq(genDat$data, eqn = EQNfile)

Generate MPT Frequencies

Description

Uses a matrix of individual MPT parameters to generate MPT frequencies.

Usage

genMPT(theta, numItems, eqnfile, restrictions, warning = TRUE)

Arguments

theta

matrix of MPT parameters (rows: individuals; columns:parameters). Parameters are assigned by column names of the matrix. all ofthe parameters in the model file need to be included.

numItems

number of responses per tree (a named vector with treelabels)

eqnfile

The (relative or full) path to the file that specifies the MPTmodel (standard .eqn syntax). Note that category labels must start with aletter (different to multiTree) and match the column names ofdata.Alternatively, the EQN-equations can be provided within R as a charactervalue (cf.readEQN). Note that the first line of an .eqn-fileis reserved for comments and always ignored.

restrictions

Specifies which parameters should be (a) constant (e.g.,"a=b=.5") or (b) constrained to be identical (e.g.,"Do=Dn")or (c) treated as fixed effects (i.e., identical for all participants;"a=b=FE"). Either given as the path to a text file with restrictionsper row or as a list of restrictions, e.g.,list("D1=D2","g=0.5").Note that numbers in .eqn-equations (e.g.,d*(1-g)*.50) are directlyinterpreted as equality constraints.

warning

whether to show warning in case the naming of data-generatingparameters are unnamed or do not match

See Also

genTraitMPT andgenBetaMPT to generatedata for latent normal/beta hierarchical distributions.

Examples

# Example: Standard Two-High-Threshold Model (2HTM)EQNfile <- system.file("MPTmodels/2htm.eqn", package = "TreeBUGS")theta <- matrix(  c(    .8, .4, .5,    .6, .3, .4  ),  nrow = 2, byrow = TRUE,  dimnames = list(NULL, c("Do", "Dn", "g")))genDat <- genMPT(  theta, c(Target = 250, Lure = 250),  EQNfile)genDat

Generate Data for Latent-Trait MPT Models

Description

Generating a data set with known parameter structure using the Trait-MPT.Useful for simulations and robustness checks.

Usage

genTraitMPT(  N,  numItems,  eqnfile,  restrictions,  mean,  mu,  sigma,  rho,  warning = TRUE)

Arguments

N

number of participants

numItems

number of responses per tree (a named vector with treelabels)

eqnfile

The (relative or full) path to the file that specifies the MPTmodel (standard .eqn syntax). Note that category labels must start with aletter (different to multiTree) and match the column names ofdata.Alternatively, the EQN-equations can be provided within R as a charactervalue (cf.readEQN). Note that the first line of an .eqn-fileis reserved for comments and always ignored.

restrictions

Specifies which parameters should be (a) constant (e.g.,"a=b=.5") or (b) constrained to be identical (e.g.,"Do=Dn")or (c) treated as fixed effects (i.e., identical for all participants;"a=b=FE"). Either given as the path to a text file with restrictionsper row or as a list of restrictions, e.g.,list("D1=D2","g=0.5").Note that numbers in .eqn-equations (e.g.,d*(1-g)*.50) are directlyinterpreted as equality constraints.

mean

named vector of data-generating group means of the individual MPTparameters on the probability scale. If the vector is not named, theinternal order of parameters is used (can be obtained usingreadEQN).

mu

an alternative way to define the group-level means on thelatent-probit scale (i.e.,mu = qnorm(mean) or equivalently,mean = pnorm(mu)).

sigma

(named) vector of group standard deviations of individual MPTparameters on the latent probit scale. Default is zero (no personheterogeneity).

rho

(named) correlation matrix for individual MPT parameters on thelatent probit scale. Must be symmetric and positive definite (e.g., nocorrelations of 1 or -1 allowed). Default: a diagonal matrix (i.e., zerocorrelations).

warning

whether to show warning in case the naming of data-generatingparameters are unnamed or do not match

Details

This functions implements a two-step sampling procedure. First, theperson parameters on the latent probit-scale are sampled from themultivariate normal distribution (based on the meanmu = qnorm(mean),the standard deviationssigma, and the correlation matrixrho).These person parameters are then transformed to the probability scale usingthe probit-link. In a last step, observed frequencies are sampled for eachperson using the MPT equations.

Note that the user can generate more complex structures for the latent personparameters, and then supply these person parameters to the functiongenMPT.

Value

a list including the generated frequencies per person (data)and the sampled individual parameters (parameters) on the probit andprobability scale (thetaLatent andtheta, respectively).

References

Klauer, K. C. (2010). Hierarchical multinomial processing treemodels: A latent-trait approach. Psychometrika, 75, 70-98.

See Also

genMPT

Examples

# Example: Standard Two-High-Threshold Model (2HTM)EQNfile <- system.file("MPTmodels/2htm.eqn", package = "TreeBUGS")rho <- matrix(c(  1, .8, .2,  .8, 1, .1,  .2, .1, 1), nrow = 3)colnames(rho) <- rownames(rho) <- c("Do", "Dn", "g")genDat <- genTraitMPT(  N = 100,  numItems = c(Target = 250, Lure = 250),  eqnfile = EQNfile,  mean = c(Do = .7, Dn = .7, g = .5),  sigma = c(Do = .3, Dn = .3, g = .15),  rho = rho)head(genDat$data, 3)plotFreq(genDat$data, eqn = EQNfile)

Get Mean Parameters per Group

Description

For hierarchical latent-trait MPT models with discrete predictor variables asfitted withtraitMPT(..., predStructure = list("f")).

Usage

getGroupMeans(  traitMPT,  factor = "all",  probit = FALSE,  file = NULL,  mcmc = FALSE)

Arguments

traitMPT

a fittedtraitMPT model

factor

whether to get group estimates for all combinations of factorlevels (default) or only for specific factors (requires the names of thecovariates in covData)

probit

whether to use probit scale or probability scale

file

filename to export results in .csv format (e.g.,file="fit_group.csv")

mcmc

ifTRUE, the raw MCMC samples for the group means arereturned as anmcmc.list object. This allows pairwisetests of group means (seetransformedParameters).

Author(s)

Daniel Heck

See Also

getParam for parameter estimates

Examples

## Not run: # save group means (probability scale):getGroupMeans(traitMPT, file = "groups.csv")## End(Not run)

Get Parameter Posterior Statistics

Description

Returns posterior statistics (e.g., mean, median) for the parameters of ahierarchical MPT model.

Usage

getParam(fittedModel, parameter = "mean", stat = "mean", file = NULL)

Arguments

fittedModel

a fitted latent-trait MPT model (seetraitMPT) or beta MPT model (seebetaMPT)

parameter

which parameter(s) of the (hierarchical) MPT model should bereturned? (see details ingetParam).

stat

whether to get the posterior"mean","median","sd", or"summary" (includes mean, SD, and 95% credibilityinterval)

file

filename to export results in .csv format (e.g.,file="est_param.csv")

Details

This function is a convenient way to get the information stored infittedModel$mcmc.summ.

The latent-trait MPT includes the following parameters:

The beta MPT includes the following parameters:

Author(s)

Daniel Heck

See Also

getGroupMeans mean group estimates

Examples

## Not run: # mean estimates per person:getParam(fittedModel, parameter = "theta")# save summary of individual estimates:getParam(fittedModel,  parameter = "theta",  stat = "summary", file = "ind_summ.csv")## End(Not run)

Get Posterior Samples from Fitted MPT Model

Description

Extracts MCMC posterior samples as ancoda::mcmc.list and relabels theMCMC variables.

Usage

getSamples(  fittedModel,  parameter = "mean",  select = "all",  names = "par_label")

Arguments

fittedModel

a fitted latent-trait MPT model (seetraitMPT) or beta MPT model (seebetaMPT)

parameter

which parameter(s) of the (hierarchical) MPT model should bereturned? (see details ingetParam).

select

character vector of parameters to be plotted (e.g.,select = c("d", "g"). Can be used to plot subsets of parameters and change the order of parameters.

names

whether and how to rename the variables in the MCMC output:par (internal parameter labels such asmu[1]),label(MPT label from EQN file such as"d"), orpar_name(concatenation of both such as"mu[1]_d").

Examples

## Not run: getSamples(fittedModel, "mu", select = c("d", "g"))## End(Not run)

Marginal Likelihood for Simple MPT

Description

Computes the marginal likelihood for simple (fixed-effects, nonhierarchical)MPT models.

Usage

marginalMPT(  eqnfile,  data,  restrictions,  alpha = 1,  beta = 1,  dataset = 1,  method = "importance",  posterior = 500,  mix = 0.05,  scale = 0.9,  samples = 10000,  batches = 10,  show = TRUE,  cores = 1)

Arguments

eqnfile

The (relative or full) path to the file that specifies the MPTmodel (standard .eqn syntax). Note that category labels must start with aletter (different to multiTree) and match the column names ofdata.Alternatively, the EQN-equations can be provided within R as a charactervalue (cf.readEQN). Note that the first line of an .eqn-fileis reserved for comments and always ignored.

data

The (relative or full) path to the .csv file with the data (commaseparated; category labels in first row). Alternatively: a data frame ormatrix (rows=individuals, columns = individual category frequencies,category labels as column names)

restrictions

Specifies which parameters should be (a) constant (e.g.,"a=b=.5") or (b) constrained to be identical (e.g.,"Do=Dn")or (c) treated as fixed effects (i.e., identical for all participants;"a=b=FE"). Either given as the path to a text file with restrictionsper row or as a list of restrictions, e.g.,list("D1=D2","g=0.5").Note that numbers in .eqn-equations (e.g.,d*(1-g)*.50) are directlyinterpreted as equality constraints.

alpha

first shape parameter(s) for the beta prior-distribution of theMPT parameters\theta_s (can be a named vector to use a differentprior for each MPT parameter)

beta

second shape parameter(s)

dataset

for which data set should Bayes factors be computed?

method

either"importance" (importance sampling using a mixtureof uniform and beta-aproximation of the posterior) or"prior" (bruteforce Monte Carlo sampling from prior)

posterior

number of posterior samples used to approximateimportance-sampling densities (i.e., beta distributions)

mix

mixture proportion of the uniform distribution for theimportance-sampling density

scale

how much should posterior-beta approximations be downscaled toget fatter importance-sampling density

samples

total number of samples from parameter space

batches

number of batches. Used to compute a standard error of theestimate.

show

whether to show progress

cores

number of CPUs used

Details

Currently, this is only implemented for a single data set!

Ifmethod = "prior", a brute-force Monte Carlo method is used andparameters are directly sampled from the prior.Then, the likelihood isevaluated for these samples and averaged (fast, but inefficient).

Alternatively, an importance sampler is used ifmethod = "importance",and the posterior distributions of the MPT parameters are approximated byindependent beta distributions. Then each parameters is sampled fromthe importance density:

mix*U(0,1) + (1-mix)*Beta(scale*a_s, scale*b_s)

References

Vandekerckhove, J. S., Matzke, D., & Wagenmakers, E. (2015).Model comparison and the principle of parsimony. In Oxford Handbook ofComputational and Mathematical Psychology (pp. 300-319). New York, NY:Oxford University Press.

See Also

BayesFactorMPT

Examples

# 2-High-Threshold Modeleqn <- "## 2HTM ##   Target  Hit  d   Target  Hit  (1-d)*g   Target  Miss (1-d)*(1-g)   Lure    FA   (1-d)*g   Lure    CR   (1-d)*(1-g)   Lure    CR   d"data <- c(  Hit = 46, Miss = 14,  FA = 14, CR = 46)# weakly informative prior for guessingaa <- c(d = 1, g = 2)bb <- c(d = 1, g = 2)curve(dbeta(x, aa["g"], bb["g"]))# compute marginal likelihoodhtm <- marginalMPT(eqn, data,  alpha = aa, beta = bb,  posterior = 200, samples = 1000)# second model: g=.50htm.g50 <- marginalMPT(eqn, data, list("g=.5"),  alpha = aa, beta = bb,  posterior = 200, samples = 1000)# Bayes factor# (per batch to get estimation error)bf <- htm.g50$p.per.batch / htm$p.per.batchmean(bf) # BFsd(bf) / sqrt(length(bf)) # standard error of BF estimate

Plot Convergence for Hierarchical MPT Models

Description

Plot Convergence for Hierarchical MPT Models

Usage

## S3 method for class 'betaMPT'plot(x, parameter = "mean", type = "default", ...)## S3 method for class 'simpleMPT'plot(x, type = "default", ...)## S3 method for class 'traitMPT'plot(x, parameter = "mean", type = "default", ...)

Arguments

x

fitted hierarchical MPT model (traitMPT,betaMPT)

parameter

which parameter to plot (e.g.,"theta","mean","rho","slope").Parameters are matched partially, in order to plot all entries of vectorvalued parameters (seegetParam to get a list of parameters).Moreover, parameter labels can be used, e.g.,"theta[D]" or"rho[D,g]"

type

type of convergence plot. Can be one of"default"(trace+density),"acf" (auto-correlation function),"trace","autocorr","crosscorr","density","gelman". See plotting functions in thecoda package(plot.mcmc.list,acfplot,traceplot,autocorr.plot,crosscorr.plot,densplot,gelman.plot).

...

further arguments passed to the plotting functions in coda

Methods (by class)


Plot Distribution of Individual Estimates

Description

Plots histograms of the posterior-means of individual MPT parameters againstthe group-level distribution given by the posterior-mean of the hierarchicalparameters (e.g., the beta distribution in case of the beta-MPT)

Usage

plotDistribution(fittedModel, scale = "probability", ...)

Arguments

fittedModel

fitted latent-trait or beta MPT model(traitMPT,betaMPT)

scale

only for latent-trait MPT: should estimates be plotted on the"latent" or the"probability" scale (i.e., as MPTparameters). Can be abbreviated by"l" and"p".

...

further arguments passed tohist (e.g.,breaks=50 to get a more fine-grained histogram)

Details

For the latent-trait MPT, differences due to continuous predictorsor discrete factors are currently not considered in the group-levelpredictions (red density). Under such a model, individual estimates are notpredicted to be normally distributed on the latent scale as shown in theplot.

See Also

plot.traitMPT


Plot Posterior Predictive Mean Frequencies

Description

Plots observed means/covariances of individual frequencies against themeans/covariances sampled from the posterior distribution (posteriorpredictive distribution).

Usage

plotFit(fittedModel, M = 1000, stat = "mean", ...)

Arguments

fittedModel

fitted latent-trait or beta MPT model (traitMPT,betaMPT)

M

number of posterior predictive samples. As a maximum, the number of posterior samples infittedModel is used.

stat

whether to plot mean frequencies ("mean") or covariancesof individual frequencies ("cov")

...

arguments passed toboxplot

Details

If posterior predictive p-values were computed when fitting themodel (e.g., by adding the argumenttraitMPT(...,ppp=1000) ), thestored posterior samples are re-used for plotting. Note that the lastcategory in each MPT tree is dropped, because one category per multinomialdistribution is fixed.

Examples

## Not run: # add posterior predictive samples to fitted model (optional step)fittedModel$postpred$freq.pred <-  posteriorPredictive(fittedModel, M = 1000)# plot model fitplotFit(fittedModel, stat = "mean")## End(Not run)

Plot Raw Frequencies

Description

Plot observed individual and mean frequencies.

Usage

plotFreq(x, freq = TRUE, select = "all", boxplot = TRUE, eqnfile, ...)

Arguments

x

either a fitted hierarchical MPT model (seetraitMPT,betaMPT); or a matrix/data frame of response frequencies (canbe provided as a path to a .csv-file with individual frequencies).

freq

whether to plot absolute frequencies or relative frequencies(which sum up to one within each tree; only ifx is a hierarchicalmodel or ifeqnfile is provided)

select

a numeric vector with participant indices to select which rawfrequencies to plot (default:"all")

boxplot

ifFALSE, lines and points are drawn instead ofboxplots

eqnfile

optional: EQN description of an MPT model, that is, either thepath to an EQN file or as a character string (only used ifx refersto a matrix/data frame or .csv-file)

...

further arguments passed toboxplot andplot

Examples

# get frequency data and EQN filefreq <- subset(arnold2013, group == "encoding", select = -(1:4))eqn <- system.file("MPTmodels/2htsm.eqn", package = "TreeBUGS")plotFreq(freq, eqnfile = eqn)plotFreq(freq, freq = FALSE, eqnfile = eqn)

Plot Parameter Estimates

Description

Plot parameter estimates for hierarchical MPT models.

Usage

plotParam(  x,  includeIndividual = TRUE,  addLines = FALSE,  estimate = "mean",  select = "all",  ...)

Arguments

x

a fitted Beta or latent-trait MPT model

includeIndividual

whether to plot individual estimates

addLines

whether to connect individual parameter estimates by lines

estimate

type of point estimates for group-level and individual parameters(either"mean" or"median")

select

character vector of parameters to be plotted (e.g.,select = c("d", "g"). Can be used to plot subsets of parameters and change the order of parameters.

...

further arguments passed to the standardplot function

Author(s)

Daniel Heck

See Also

betaMPT,traitMPT,plotDistribution

Examples

## Not run: plotParam(fit,  addLines = TRUE,  estimate = "median",  select = c("d1", "d2"))## End(Not run)

Plot Prior Distributions

Description

Plots prior distributions for group means, standard deviation, andcorrelations of MPT parameters across participants.

Usage

plotPrior(prior, probitInverse = "mean", M = 5000, nCPU = 3, ...)

Arguments

prior

a named list defining the priors. For thetraitMPT, thedefault islist(mu = "dnorm(0,1)", xi="dunif(0,10)", V=diag(S),df=S+1), where S is the number of free parameters. For thebetaMPT,the default islist(alpha ="dgamma(1,.1)", beta = "dgamma(1,.1)").Note that the normal distribution"dnorm(mu,prec)" is parameterizedas in JAGS by the mean and precision (= 1/variance).

probitInverse

which latent-probit parameters (fortraitMPT model) to transform to probability scale. Either"none","mean" (simple transformation\Phi(\mu)), or"mean_sd" (seeprobitInverse)

M

number of random samples to approximate priors of group-levelparameters

nCPU

number of CPUs used for parallel sampling. For large models andmany participants, this may require a lot of memory.

...

further arguments passed toplot

Details

This function samples from a set of hyperpriors (either forhierarchical traitMPT or betaMPT structure) to approximate the impliedprior distributions on the parameters of interest (group-level mean, SD,and correlations of MPT parameters). Note that the normal distribution"dnorm(mu,prec)" is parameterized as in JAGS by the mean andprecision (= 1/variance).

See Also

priorPredictive

Examples

## Not run: # default priors for traitMPT:plotPrior(list(  mu = "dnorm(0, 1)",  xi = "dunif(0, 10)",  V = diag(2),  df = 2 + 1), M = 4000)# default priors for betaMPT:plotPrior(list(  alpha = "dgamma(1, 0.1)",  beta = "dgamma(1, 0.1)"), M = 4000)## End(Not run)

Plot Prior vs. Posterior Distribution

Description

Allows to judge how much the data informed the parameter posteriordistributions compared to the prior.

Usage

plotPriorPost(  fittedModel,  probitInverse = "mean",  M = 2e+05,  ci = 0.95,  nCPU = 3,  ...)

Arguments

fittedModel

fitted latent-trait or beta MPT model (traitMPT,betaMPT)

probitInverse

which latent-probit parameters (fortraitMPT model) to transform to probability scale. Either"none","mean" (simple transformation\Phi(\mu)), or"mean_sd" (seeprobitInverse)

M

number of random samples to approximate prior distributions

ci

credibility interval indicated by vertical red lines

nCPU

number of CPUs used for parallel sampling. For large models andmany participants, this may require a lot of memory.

...

arguments passed toboxplot

Details

Prior distributions are shown as blue, dashed lines, whereasposterior distributions are shown as solid, black lines.


Get Posterior Predictive Samples

Description

Draw predicted frequencies based on posterior distribution of (a) individual estimates (default) or (b) for a new participant (ifnumItems is provided; does not consider continuous or discrete predictors in traitMPT).

Usage

posteriorPredictive(  fittedModel,  M = 100,  numItems = NULL,  expected = FALSE,  nCPU = 4)

Arguments

fittedModel

fitted latent-trait or beta MPT model (traitMPT,betaMPT)

M

number of posterior predictive samples. As a maximum, the number of posterior samples infittedModel is used.

numItems

optional: a vector with the number of items per MPT tree to sample predicted data for a new participant (first, a participant vector\theta is sampled from the hierarchical posterior; second, frequencies are generated).

expected

ifTRUE, the expected frequencies per person are returned (without additional sampling from a multinomial distribution)

nCPU

number of CPUs used for parallel sampling. For large models and many participants, this requires considerable computer-memory resources (as a remedy, usenCPU=1).

Value

by default, a list ofM posterior-predictive samples (i.e., matrices) with individual frequencies (rows=participants, columns=MPT categories). ForM=1, a single matrix is returned. IfnumItems is provided, a matrix with samples for a new participant is returned (rows=samples)

Examples

## Not run: # add posterior predictive samples to fitted model#     (facilitates plotting using ?plotFit)fittedModel$postpred$freq.pred <-  posteriorPredictive(fittedModel, M = 1000)## End(Not run)

Prior Predictive Samples

Description

Samples full data sets (i.e., individual response frequencies) or group-levelMPT parameters based on prior distribution for group-level parameters.

Usage

priorPredictive(  prior,  eqnfile,  restrictions,  numItems,  level = "data",  N = 1,  M = 100,  nCPU = 4)

Arguments

prior

a named list defining the priors. For thetraitMPT, thedefault islist(mu = "dnorm(0,1)", xi="dunif(0,10)", V=diag(S),df=S+1), where S is the number of free parameters. For thebetaMPT,the default islist(alpha ="dgamma(1,.1)", beta = "dgamma(1,.1)").Note that the normal distribution"dnorm(mu,prec)" is parameterizedas in JAGS by the mean and precision (= 1/variance).

eqnfile

The (relative or full) path to the file that specifies the MPTmodel (standard .eqn syntax). Note that category labels must start with aletter (different to multiTree) and match the column names ofdata.Alternatively, the EQN-equations can be provided within R as a charactervalue (cf.readEQN). Note that the first line of an .eqn-fileis reserved for comments and always ignored.

restrictions

Specifies which parameters should be (a) constant (e.g.,"a=b=.5") or (b) constrained to be identical (e.g.,"Do=Dn")or (c) treated as fixed effects (i.e., identical for all participants;"a=b=FE"). Either given as the path to a text file with restrictionsper row or as a list of restrictions, e.g.,list("D1=D2","g=0.5").Note that numbers in .eqn-equations (e.g.,d*(1-g)*.50) are directlyinterpreted as equality constraints.

numItems

vector with the number of items per MPT tree (either named orassigned to alphabetically ordered tree labels)

level

either"data" (returns individual frequencies) or"parameter" (returns group-level MPT parameters;M andnumItems are ignored)

N

number of participants per replication

M

number of prior predictive samples (i.e., data sets withNparticipants).

nCPU

number of CPUs used for parallel sampling. For large models andmany participants, this may require a lot of memory.

Value

a list ofM matrices with individual frequencies(rows=participants, columns=MPT categories). A single matrix is returned ifM=1 orlevel="parameter".

Examples

eqnfile <- system.file("MPTmodels/2htm.eqn",  package = "TreeBUGS")### beta-MPT:prior <- list(  alpha = "dgamma(1,.1)",  beta = "dgamma(1,.1)")### prior-predictive frequencies:priorPredictive(prior, eqnfile,  restrictions = list("g=.5", "Do=Dn"),  numItems = c(50, 50), N = 10, M = 1, nCPU = 1)### prior samples of group-level parameters:priorPredictive(prior, eqnfile,  level = "parameter",  restrictions = list("g=.5", "Do=Dn"),  M = 5, nCPU = 1)### latent-trait MPTpriorPredictive(  prior = list(    mu = "dnorm(0,1)", xi = "dunif(0,10)",    df = 3, V = diag(2)  ),  eqnfile, restrictions = list("g=.5"),  numItems = c(50, 50), N = 10, M = 1, nCPU = 1)

Probit-Inverse of Group-Level Normal Distribution

Description

Transform latent group-level normal distribution (latent-trait MPT) into meanand SD on probability scale.

Usage

probitInverse(mu, sigma, fittedModel = NULL)

Arguments

mu

latent-probit mean of normal distribution

sigma

latent-probit SD of normal distribution

fittedModel

optional: fittedtraitMPT model. If provided, thebivariate inverse-probit transform is applied to all MCMC samples (andmu andsigma are ignored).

Value

implied mean and SD on probability scale

Examples

####### compare bivariate vs. univariate transformationprobitInverse(mu = 0.8, sigma = c(0.25, 0.5, 0.75, 1))pnorm(0.8)# full distributionprob <- pnorm(rnorm(10000, mean = 0.8, sd = 0.7))hist(prob, 80, col = "gray", xlim = 0:1)## Not run: # transformation for fitted modelmean_sd <- probitInverse(fittedModel = fit)summarizeMCMC(mean_sd)## End(Not run)

Read multiTree files

Description

Function to import MPT models from standard .eqn model files as used, forinstance, by multiTree (Moshagen, 2010).

Usage

readEQN(file, restrictions = NULL, paramOrder = FALSE, parse = FALSE)

Arguments

file

The (full path to the) file that specifies the MPT model(standard .eqn syntax). Note that category labels must start with a letter(different to multiTree) and match the column names ofdata.Alternatively, the EQN-equations can be provided within R as a charactervalue (see examples). Note that the first line of an .eqn-file is reservedfor comments and always ignored.

restrictions

Specifies which parameters should be (a) constant (e.g.,"a=b=.5") or (b) constrained to be identical (e.g.,"Do=Dn")or (c) treated as fixed effects (i.e., identical for all participants;"a=b=FE"). Either given as the path to a text file with restrictionsper row or as a list of restrictions, e.g.,list("D1=D2","g=0.5").Note that numbers in .eqn-equations (e.g.,d*(1-g)*.50) are directlyinterpreted as equality constraints.

paramOrder

if TRUE, the order of MPT parameters as interally used isprinted.

parse

whether to return a parsed MPT model description in terms of thematricesa andb (the powers of the\theta and(1-\theta), respectively, and the vector of constantsc. Eachbranch probability is then given asc_{i} \prod_{s}\theta^{a_{i,s}}(1-\theta)^{b_{i,s}})

Details

The file format should adhere to the standard .eqn-syntax (note thatthe first line is skipped and can be used for comments). In each line, aseparate branch of the MPT model is specified using the tree label,category label, and the model equations in full form (multiplication sign* required; not abbreviations such asa^2 allowed).

As an example, the standard two-high threshold model (2HTM) is defined asfollows:

TargetHitDo
TargetHit(1-Do)*g
TargetMiss(1-Do)*(1-g)
LureFalseAlarm(1-Dn)*g
LureCorrectReject(1-Dn)*(1-g)
LureCorrectRejectDn

Value

for the default settingparse = FALSE, the function returns adata.frame with the following columns:

Author(s)

Daniel Heck, Denis Arnold, Nina Arnold

References

Moshagen, M. (2010). multiTree: A computer program for theanalysis of multinomial processing tree models. Behavior Research Methods,42, 42-54.

Examples

# Example: Standard Two-High-Threshold Model (2HTM)EQNfile <- system.file("MPTmodels/2htm.eqn",  package = "TreeBUGS")readEQN(file = EQNfile, paramOrder = TRUE)# with equality constraint:readEQN(  file = EQNfile, restrictions = list("Dn = Do", "g = 0.5"),  paramOrder = TRUE)# define MPT model directly within Rmodel <-  "2-High Threshold Model (2HTM)  old hit d  old hit (1-d)*g  old miss (1-d)*(1-g)  new fa (1-d)*g  new cr (1-d)*(1-g)  new cr d"readEQN(model, paramOrder = TRUE)

C++ Sampler for Standard (Nonhierarchical) MPT Models

Description

Fast Gibbs sampler in C++ that is tailored to the standard fixed-effects MPTmodel (i.e., fixed-effects, non-hierarchical MPT). Assumes independentparameters per person if a matrix of frequencies per person is supplied.

Usage

simpleMPT(  eqnfile,  data,  restrictions,  n.iter = 2000,  n.burnin = 500,  n.thin = 3,  n.chains = 3,  ppp = 0,  alpha = 1,  beta = 1,  parEstFile,  posteriorFile,  cores = 1)

Arguments

eqnfile

The (relative or full) path to the file that specifies the MPTmodel (standard .eqn syntax). Note that category labels must start with aletter (different to multiTree) and match the column names ofdata.Alternatively, the EQN-equations can be provided within R as a charactervalue (cf.readEQN). Note that the first line of an .eqn-fileis reserved for comments and always ignored.

data

The (relative or full) path to the .csv file with the data (commaseparated; category labels in first row). Alternatively: a data frame ormatrix (rows=individuals, columns = individual category frequencies,category labels as column names)

restrictions

Specifies which parameters should be (a) constant (e.g.,"a=b=.5") or (b) constrained to be identical (e.g.,"Do=Dn")or (c) treated as fixed effects (i.e., identical for all participants;"a=b=FE"). Either given as the path to a text file with restrictionsper row or as a list of restrictions, e.g.,list("D1=D2","g=0.5").Note that numbers in .eqn-equations (e.g.,d*(1-g)*.50) are directlyinterpreted as equality constraints.

n.iter

Number of iterations per chain (including burnin samples). Seerun.jags for details.

n.burnin

Number of samples for burnin (samples will not be stored andremoved from n.iter)

n.thin

Thinning rate.

n.chains

number of MCMC chains (sampled in parallel, which can bechanged via the additional argumentn.sim = 1).

ppp

number of samples to compute posterior predictive p-value (seeposteriorPredictive)

alpha

first shape parameter(s) for the beta prior-distribution of theMPT parameters\theta_s (can be a named vector to use a differentprior for each MPT parameter)

beta

second shape parameter(s)

parEstFile

Name of the file to with the estimates should be stored(e.g., "parEstFile.txt")

posteriorFile

path to RData-file where to save the model includingMCMC posterior samples (an object namedfittedModel; e.g.,posteriorFile="mcmc.RData")

cores

number of CPUs to be used

Details

Beta distributions with fixed shape parameters\alpha and\beta are used. The default\alpha=1 and\beta=1 assumesuniform priors for all MPT parameters.

Author(s)

Daniel Heck

Examples

## Not run: # fit nonhierarchical MPT model for aggregated data (see ?arnold2013):EQNfile <- system.file("MPTmodels/2htsm.eqn", package = "TreeBUGS")d.encoding <- subset(arnold2013, group == "encoding", select = -(1:4))fit <- simpleMPT(EQNfile, colSums(d.encoding),  restrictions = list("D1=D2=D3", "d1=d2", "a=g"))# convergenceplot(fit)summary(fit)## End(Not run)

MCMC Summary

Description

TreeBUGS-specific MCMC summary formcmc.list-objects.

Usage

summarizeMCMC(mcmc, batchSize = 50, probs = c(0.025, 0.5, 0.975))

Arguments

mcmc

amcmc.list object

batchSize

size of batches of parameters used to reduce memory loadwhen computing posterior summary statistics (including Rhat and effectivesample size).

probs

quantile probabilities used to compute credibility intervals


Summarize JAGS Output for Hierarchical MPT Models

Description

Provide clean and readable summary statistics tailored to MPT models based onthe JAGS output.

Usage

summarizeMPT(mcmc, mptInfo, probs = c(0.025, 0.5, 0.975), summ = NULL)

Arguments

mcmc

the actual mcmc.list output of the sampler of a fitted MPT model(accesible viafittedModel$runjags$mcmc)

mptInfo

the internally stored information about the fitted MPT model(accesible viafittedModel$mptInfo)

probs

quantile probabilities used to compute credibility intervals

summ

optional argument for internal use

Details

The MPT-specific summary is computed directly after fitting a model.However, this function might be used manually after removing MCMC samples(e.g., extending the burnin period).

Examples

# Remove additional burnin samples and recompute MPT summary## Not run: # start later or thin (see ?window)mcmc.subsamp <- window(fittedModel$runjags$mcmc, start = 3001, thin = 2)new.mpt.summary <- summarizeMPT(mcmc.subsamp, fittedModel$mptInfo)new.mpt.summary## End(Not run)

Chi-Square Test of Heterogeneity

Description

Tests whether whether participants (items) are homogeneous under theassumption of item (participant) homogeneity.

Usage

testHetChi(freq, tree)

Arguments

freq

matrix with observed frequencies (rows: persons/items; columns:categories). Can also be the path to a .csv file with frequencies(comma-separated; first line defines category labels)

tree

a vector defining which columns of x belong to separatemultinomial distributions (i.e., MPT trees). For instance, ifx hasfive categories from two MPT trees:tree=c(1,1,2,2,2) ortree=c("t1","t1","t2","t2","t2")

Details

If an item/person has zero frequencies on all categories in an MPTtree, these zeros are neglected when computing mean frequencies per column.As an example, consider a simple recognition test with a fixed assignments ofwords to the learn/test list. In such an experiment, all learned words willresult in hits or misses (i.e., the MPT tree of old items), whereas new wordsare always false alarms/correct rejections and thus belong to the MPT tree ofnew items (this is not necessarily the case if words are assigned randomly).

Note that the test assumes independence of observations and item homogeneitywhen testing participant heterogeneity. The latter assumption can be droppedwhen using a permutation test (testHetPerm).

Author(s)

Daniel W. Heck

References

Smith, J. B., & Batchelder, W. H. (2008). Assessing individualdifferences in categorical data. Psychonomic Bulletin & Review, 15,713-731.doi:10.3758/PBR.15.4.713

See Also

testHetPerm,plotFreq

Examples

# some made up frequencies:freq <- matrix(  c(    13, 16, 11, 13,    15, 21, 18, 13,    21, 14, 16, 17,    19, 20, 21, 18  ),  ncol = 4, byrow = TRUE)# for a product-binomial distribution:# (categories 1 and 2 and categories 3 and 4 are binomials)testHetChi(freq, tree = c(1, 1, 2, 2))# => no significant deviation from homogeneity (low power!)

Permutation Test of Heterogeneity

Description

Tests whether whether participants (items) are homogeneous without assumingitem (participant) homogeneity.

Usage

testHetPerm(data, tree, source = "person", rep = 1000, nCPU = 4)

Arguments

data

matrix or data frame with three columns: person code/index, itemlabel, response category. Can also be the path to a .csv file withfrequencies (comma-separated; first line defines category labels)

tree

a list that defines which categories belong to the samemultinomial distribution (i.e., the the same MPT tree). For instance:tree = list(tree.old = c("hit","cr"), tree.new = c("fa","miss")).Category labels must match the values of the third column ofdata

source

whether to test for"person" or"item"homogeneity

rep

number of permutations to be sampled

nCPU

number of CPUs used for parallel Monte Carlo sampling ofpermutations

Details

If an item/person has zero frequencies on all categories in an MPTtree, these zeros are neglected when computing mean frequencies per column.As an example, consider a simple recognition test with a fixed assignments ofwords to the learn/test list. In such an experiment, all learned words willresult in hits or misses (i.e., the MPT tree of old items), whereas new wordsare always false alarms/correct rejections and thus belong to the MPT tree ofnew items (this is not necessarily the case if words are assigned randomly).

Note that the test does still assume independence of observations. However,it does not require item homogeneity when testing participant heterogeneity(in contrast to the chi-square test:testHetChi).

Author(s)

Daniel W. Heck

References

Smith, J. B., & Batchelder, W. H. (2008). Assessing individualdifferences in categorical data. Psychonomic Bulletin & Review, 15,713-731.doi:10.3758/PBR.15.4.713

See Also

testHetChi,plotFreq

Examples

# generate homogeneous data# (N=15 participants, M=30 items)data <- data.frame(  id = rep(1:15, each = 30),  item = rep(1:30, 15))data$cat <- sample(c("h", "cr", "m", "fa"), 15 * 30,  replace = TRUE,  prob = c(.7, .3, .4, .6))head(data)tree <- list(  old = c("h", "m"),  new = c("fa", "cr"))# test participant homogeneity:tmp <- testHetPerm(data, tree, rep = 200, nCPU = 1)tmp[2:3]

Fit a Hierarchical Latent-Trait MPT Model

Description

Fits a latent-trait MPT model (Klauer, 2010) based on a standard MPT modelfile (.eqn) and individual data table (.csv).

Usage

traitMPT(  eqnfile,  data,  restrictions,  covData,  predStructure,  predType,  transformedParameters,  corProbit = TRUE,  mu = "dnorm(0,1)",  xi = "dunif(0,10)",  V,  df,  IVprec = "dgamma(.5,.5)",  n.iter = 20000,  n.adapt = 2000,  n.burnin = 2000,  n.thin = 5,  n.chains = 3,  dic = FALSE,  ppp = 0,  monitorIndividual = TRUE,  modelfilename,  parEstFile,  posteriorFile,  autojags = NULL,  ...)

Arguments

eqnfile

The (relative or full) path to the file that specifies the MPTmodel (standard .eqn syntax). Note that category labels must start with aletter (different to multiTree) and match the column names ofdata.Alternatively, the EQN-equations can be provided within R as a charactervalue (cf.readEQN). Note that the first line of an .eqn-fileis reserved for comments and always ignored.

data

The (relative or full) path to the .csv file with the data (commaseparated; category labels in first row). Alternatively: a data frame ormatrix (rows=individuals, columns = individual category frequencies,category labels as column names)

restrictions

Specifies which parameters should be (a) constant (e.g.,"a=b=.5") or (b) constrained to be identical (e.g.,"Do=Dn")or (c) treated as fixed effects (i.e., identical for all participants;"a=b=FE"). Either given as the path to a text file with restrictionsper row or as a list of restrictions, e.g.,list("D1=D2","g=0.5").Note that numbers in .eqn-equations (e.g.,d*(1-g)*.50) are directlyinterpreted as equality constraints.

covData

Data that contains covariates, for which correlations withindividual MPT parameters will be sampled. Either the path to a .csv file(comma-separated: rows=individuals in the same order asdata; firstrow must contain covariate labels). Alternatively: a data frame or matrix(rows=individuals, columns = variables; covariate labels as column names).Note that inbetaMPT, correlations are computed for discretevariables that are coded numerically (intraitMPT, this can besuppressed by usingpredType="f")

predStructure

Defines which variables incovData are includedas predictors for which MPT parameters. Either the path to the file thatspecifies the assignment of MPT parameters to covariates (that is, each rowassigns one or more MPT parameters to one or more covariates, separated bya semicolon, e.g.,Do g; age extraversion). Can also be provided asa list, e.g.,list("Do Dn ; age", "g ; extraversion"). Note that nocorrelations of MPT parameters and predictors are computed. However, forcontinuous covariates, the standardized slope parametersslope_std_parameter_predictor can be interpreted as a correlation ifa single predictor is included for the corresponding MPT parameter (seeJobst et al., 2020).

predType

a character vector specifying the type of continuous ordiscrete predictors in each column ofcovData:"c" =continuous covariate (which are centered to have a mean of zero);"f" = discrete predictor, fixed effect (default for character/factorvariables);"r" = discrete predictor, random effect.

transformedParameters

list with parameter transformations that shouldbe computed based on the posterior samples of the group-level means (e.g.,for testing parameter differences:list("diffD=Do-Dn")), or path toa text file containing one transformation per line. Transformations ofindividual-level parameters can also be performed after fitting a modelusingtransformedParameters.

corProbit

whether to use probit-transformed MPT parameters to computecorrelations (probit-values of+Inf are truncated tomax(5,max(probit)); similarly for-Inf). Default forbeta-MPT: MPT parameters are used on the probability scale [0,1].

mu

hyperprior for group means of probit-transformed parameters in JAGSsyntax. Default is a standard normal distribution, which implies a uniformdistribution on the MPT probability parameters. A named vector can be usedto specify separate hyperpriors for each MPT parameter (the order ofparameters is determined by the names of the vector or by the default orderas shown inreadEQN withparamOrder = TRUE).

xi

hyperprior for scaling parameters of the group-level parametervariances. Default is a uniform distribution on the interval [0,10].Similarly as formu, a vector of different priors can be used. Lessinformative priors can be used (e.g.,"dunif(0,100)")) but mightresult in reduced stability.

V

S x S matrix used as a hyperprior for the inverse-Wisharthyperprior parameters with as many rows and columns as there are core MPTparameters. Default is a diagonal matrix.

df

degrees of freedom for the inverse-Wishart hyperprior for theindividual parameters. Minimum is S+1, where S gives the number of core MPTparameters.

IVprec

hyperprior on the precision parameterg (= the inverse ofthe variance) of the standardized slope parameters of continuouscovariates. The defaultIVprec=dgamma(.5,.5) defines a mixture ofg-priors (also known as JZS or Cauchy prior) with the scale parameters=1. Different scale parameterss can be set via:IVprec=dgamma(.5,.5*s^2). A numeric constantIVprec=1 impliesag-prior (a normal distribution). For ease of interpretation,TreeBUGS reports both unstandardized and standardized regressioncoefficients. See details below.

n.iter

Number of iterations per chain (including burnin samples). Seerun.jags for details.

n.adapt

number of adaption samples to adjust MCMC sampler in JAGS. Thesampler will be more efficient if it is tuned well. However, MCMC samplingwill still give correct results even if the warning appears: "Adaptationincomplete." (this just means that sampling efficiency could be better).

n.burnin

Number of samples for burnin (samples will not be stored andremoved from n.iter)

n.thin

Thinning rate.

n.chains

number of MCMC chains (sampled in parallel, which can bechanged via the additional argumentn.sim = 1).

dic

whether to compute DIC usingextract.runjags, which requires additional sampling.Can also be computed and added after fitting the model byfittedModel$summary$dic <- runjags::extract(fittedModel$runjags,"dic"). As an alternative information criterion,WAIC can becomputed for fitted models.

ppp

number of samples to compute posterior predictive p-value (seeposteriorPredictive)

monitorIndividual

whether to store MCMC samples of the MPTparameterstheta at the individual level (i.e., the random effects).IfFALSE, it is not possible to perform posterior-predictive checks.

modelfilename

name of the generated JAGS model file. Default is towrite this information to the tempdir as required by CRAN standards.

parEstFile

Name of the file to with the estimates should be stored(e.g., "parEstFile.txt")

posteriorFile

path to RData-file where to save the model includingMCMC posterior samples (an object namedfittedModel; e.g.,posteriorFile="mcmc.RData")

autojags

JAGS first fits the MPT model as usual and then draws MCMCsamples repeatedly until convergence. For this, the functionautoextend.jags is used with the arguments provided inautojags (this can be an empty list, in which case the defaults areused). Possible arguments forautoextend.jags are:list(startburnin = 1000, startsample = 5000, adapt = 2000,max.time="30m") (the last of these arguments restricts sampling to 30minutes, seeautoextend.jags).

...

further arguments passed to the JAGS sampling functionrun.jags. The number of CPUs/cores forthe"parallel" method can be changed via the argumentn.sim = 1.It is also possible to provide an existingparallel cluster objectvia the argumentcl. Reproducible results can beobtained by setting a random seed before fitting a model (i.e.,set.seed(12345) ).

Value

a list of the classtraitMPT with the objects:

Regression Extensions

Continuous and discrete predictors are addedon the latent-probit scale via:

\theta = \Phi(\mu + X \beta +\delta ),

whereX is a design matrix includes centered continuouscovariates and recoded factor variables (using the orthogonal contrastcoding scheme by Rouder et al., 2012). Note that both centering andrecoding is done internally. TreeBUGS reports unstandardized regressioncoefficients\beta that correspond to the scale/SD of the predictorvariables. Hence, slope estimates will be very small if the covariate has alarge variance. TreeBUGS also reports standardized slope parameters(labeled withstd) which are standardized both with respect to thevariance of the predictor variables and the variance in the individual MPTparameters. If a single predictor variable is included, the standardizedslope can be interpreted as a correlation coefficient (Jobst et al., 2020).

For continuous predictor variables, the default priorIVprec = "dgamma(.5,.5)" implies a Cauchy prior on the\beta parameters(standardized with respect to the variance of the predictor variables).This prior is similar to the Jeffreys-Zellner-Siow (JZS) prior with scaleparameters=1 (for details, see: Rouder et. al, 2012; Rouder & Morey,2012). In contrast to the JZS prior for standard linear regression byRouder & Morey (2012), TreeBUGS implements a latent-probit regression wherethe prior on the coefficients\beta is only standardized/scaled withrespect to the continuous predictor variables but not with respect to theresidual variance (since this is not a parameter in probit regression). Ifsmall effects are expected, smaller scale valuess can be used bychanging the default toIVprec = 'dgamma(.5, .5*s^2)' (by pluggingin a specific number fors). To use a standard-normal instead of aCauchy prior distribution, useIVprec = 'dcat(1)'. Bayes factors forslope parameters of continuous predictors can be computed with the functionBayesFactorSlope.

Uncorrelated Latent-Trait Values

The standard latent-trait MPTmodel assumes a multivariate normal distribution of the latent-traitvalues, where the covariance matrix follows a scaled-inverse Wishartdistribution. As an alternative, the parameters can be assumed to beindependent (this is equivalent to a diagonal covariance matrix). If theassumption of uncorrelated parameters is justified, such a simplified modelhas less parameters and is more parsimonious, which in turn might result inmore robust estimation and more precise parameter estimates.

This alternative method can be fitted in TreeBUGS (but not all of thefeatures of TreeBUGS might be compatible with this alternative modelstructure). To fit the model, the scale matrixV is set toNA(V is only relevant for the multivariate Wishart prior) and the prior onxi is changed:traitMPT(..., V=NA, xi="dnorm(0,1)"). Themodel assumes that the latent-trait values\delta_i(=random-intercepts) are decomposed by the scaling parameter\xi andthe raw deviation\epsilon_i (cf. Gelman, 2006):

\delta_i = \xi \cdot \epsilon_i

\epsilon_i \sim Normal(0,\sigma^2)

\sigma^2 \sim Inverse-\chi^2(df)

Note that the default prior for\xi shouldbe changed toxi="dnorm(0,1)", which results in a half-Cauchy prior(Gelman, 2006).

Author(s)

Daniel W. Heck, Denis Arnold, Nina R. Arnold

References

Heck, D. W., Arnold, N. R., & Arnold, D. (2018). TreeBUGS: An Rpackage for hierarchical multinomial-processing-tree modeling.BehaviorResearch Methods, 50, 264–284.doi:10.3758/s13428-017-0869-7

Gelman, A. (2006). Prior distributions for variance parameters inhierarchical models (comment on article by Browne and Draper).BayesianAnalysis, 1, 515-534.

Jobst, L. J., Heck, D. W., & Moshagen, M. (2020). A comparison of correlationand regression approaches for multinomial processing tree models.Journal of Mathematical Psychology, 98, 102400.doi:10.1016/j.jmp.2020.102400

Klauer, K. C. (2010). Hierarchical multinomial processing tree models: Alatent-trait approach.Psychometrika, 75, 70-98.doi:10.1007/s11336-009-9141-0

Matzke, D., Dolan, C. V., Batchelder, W. H., & Wagenmakers, E.-J. (2015).Bayesian estimation of multinomial processing tree models with heterogeneityin participants and items.Psychometrika, 80, 205-235.doi:10.1007/s11336-013-9374-9

Rouder, J. N., Morey, R. D., Speckman, P. L., & Province, J. M. (2012).Default Bayes factors for ANOVA designs.Journal of MathematicalPsychology, 56, 356-374.doi:10.1016/j.jmp.2012.08.001

Rouder, J. N., & Morey, R. D. (2012). Default Bayes Factors for ModelSelection in Regression.Multivariate Behavioral Research, 47,877-903.doi:10.1080/00273171.2012.734737

Examples

## Not run: # fit beta-MPT model for encoding condition (see ?arnold2013):EQNfile <- system.file("MPTmodels/2htsm.eqn", package = "TreeBUGS")d.encoding <- subset(arnold2013, group == "encoding", select = -(1:4))fit <- traitMPT(EQNfile, d.encoding,  n.thin = 5,  restrictions = list("D1=D2=D3", "d1=d2", "a=g"))# convergenceplot(fit, parameter = "mean", type = "default")summary(fit)## End(Not run)

Get Transformed Parameters

Description

Computes transformations of MPT parameters based on the MCMC posteriorsamples (e.g., differences of parameters).

Usage

transformedParameters(  fittedModel,  transformedParameters,  level = "group",  nCPU = 4)

Arguments

fittedModel

either a fitted latent-trait or beta MPT model(traitMPT,betaMPT) or anmcmc.list.

transformedParameters

list with parameter transformations that shouldbe computed based on the posterior samples (e.g., for testing parameterdifferences:list("diffD=Do-Dn")).

level

whether to compute transformations of"group" or"individual" estimates

nCPU

number of CPU cores across which the MCMC chains are distributed

Value

anmcmc.list of posterior samples for the transformedparameters

Examples

## Not run: tt <- transformedParameters(fittedModel,  list("diff = a-b", "p = a>b"),  level = "individual")summary(tt)## End(Not run)

Generate EQN Files for Within-Subject Designs

Description

Replicates an MPT model multiple times with different tree, category, andparameter labels for within-subject factorial designs.

Usage

withinSubjectEQN(eqnfile, labels, constant, save)

Arguments

eqnfile

The (relative or full) path to the file that specifies the MPTmodel (standard .eqn syntax). Note that category labels must start with aletter (different to multiTree) and match the column names ofdata.Alternatively, the EQN-equations can be provided within R as a charactervalue (cf.readEQN). Note that the first line of an .eqn-fileis reserved for comments and always ignored.

labels

a character vector defining the labels that are added to theparameters in each within-subject condition

constant

optional: a character vector defining which parameters areconstrained to be constant across within-conditions

save

optional: path to an EQN output file. By default, the model isreturn as a string character

Examples

# Example: Standard Two-High-Threshold Model (2HTM)EQNfile <- system.file("MPTmodels/2htm.eqn",  package = "TreeBUGS")withinSubjectEQN(EQNfile, c("high", "low"), constant = c("g"))

[8]ページ先頭

©2009-2025 Movatter.jp