---
title: "Introduction to D3mirt Analysis"
author: "Erik Forsberg"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to D3mirt Analysis}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
editor_options: 
  markdown: 
    wrap: sentence
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r setup, message = FALSE}
library(D3mirt)
library(mirt)
knitr::knit_hooks$set(webgl = hook_webgl)
```

::: {align="center"}
<img src="https://github.com/ForsbergPyschometrics/D3mirt/raw/main/man/figures/logo.png" align="center" height="200"/>
:::

# `D3MIRT` Modeling

The `D3mirt` analysis is based on descriptive multidimensional item response theory (DMIRT; Reckase, 2009, 1985; Reckase & McKinley, 1991) and can be used to analyze dichotomous and polytomous items (see Muraki & Carlson, 1995) in a three-dimensional ability space.
The method is foremost visual and illustrates item characteristics with the help of vector geometry in which items are represented by vector arrows.

In DMIRT analysis, also called within multidimensional modeling, it is assumed that items in a multidimensional ability space can measure single or multiple latent traits (Reckase, 2009, 1985; Reckase & McKinley, 1991).
The methodology is a type of data reduction technique based on the compensatory model (Reckase, 2009), i.e., a type of measurement model that uses linear combinations of $\theta$-values for ability assessment.
The method seeks to maximize item discrimination and so is *descriptive* because the results describe the extent to which items in a test are unidimensional, i.e., that the items discriminate on one dimension only, or are within-multidimensional, i.e., that the items discriminate on more than one dimension..

Regarding vector orientation, the angle of the vector arrows indicates what traits, located along the orthogonal axes in the model, an item can be said to describe (Reckase, 2009, 1985, Reckase & McKinley, 1991).
For instance, in a two-dimensional space, an item is *unidimensional* if its item vector arrow is at $0°$ with respect to one of the axes in the model, and $90°$ with respect to the other.
Such an item describes a singular trait only.
In contrast, an item is *within-multidimensional* if its item vector arrow is oriented at $45°$ in relation to the axes in the model.
Such an item describes both traits in the model equally well.
The same criteria are extended to the three-dimensional case.

The DMIRT approach uses two types of item models, dependent on item type.
If dichotomous items are used, the analysis is based on the two-parameter logistic model (M2PL).
If polytomous items are used, the analysis is extended to the two-parameter graded response model (MGRM; Muraki & Carlson, 1995).
In both cases, the estimation process consists of first fitting a compensatory multidimensional two-parameter model so that discrimination and difficulty ($a$ and $d$) parameters can be extracted.
For `D3mirt`, this implies that a compensatory three-dimensional M2PL or MGRM must be fitted.
Next, using these parameters the DMIRT computation finds the direction of the highest possible discrimination slope for each item.
The direction, in turn, shows what latent trait the item can be said to measure in the multidimensional latent model.
The output can be visualized as vector arrows representing item response functions located in a multidimensional space pointing in the direction of the maximum slope.
The `D3mirt()` function can be used to calculate all necessary estimates for a three-dimensional DMIRT model, as well as to plot the results.

The most central estimates, briefly explained below, in DMIRT analysis are the single multidimensional discrimination ($MDISC$) parameter, the multidimensional difficulty ($MDIFF$) parameters, and the directional discrimination ($DDISC$) parameters (Reckase2009, 1985; Reckase & McKinley, 1991).
For reasons of simplicity, the fundamentals of DMIRT theory will be presented below limited to the two-dimensional case and the M2PL.
The estimates will also be presented under the assumption that the axes $l$ are orthogonal.
This introduces the constraint that $\sum_{l=1}^{m}cos^2\alpha_{jl} = 1$, i.e., that squared cosines equal $1$ so that $cos^2\, \alpha_{im} = 1-\sum_{k=1}^{m-1} cos^2\, \alpha_{ik}$, for item $i$, person $j$, and $k$ orthogonal axes.

The $MDISC$ for item $i$ represents the highest level of discrimination the item $i$ can achieve located in a multidimensional latent trait space (also called the point of inflection), with $m$ number of dimensions and $a_{ik}$ item slope parameters (Reckase, 2009, Reckase & McKinley, 1991).

::: {align="center"}
$MDISC = A_i = \sqrt {\sum_{k = 1}^{m} a^{2}_{ik} }$
:::

Similarly to unidimensional modeling, the $MDISC$ parameter, also denoted as $A_i$, is the parameter that set the steepness of the slope of the item response function at the point of inflection.
The slope is, similarly to the unidimensional case, assessed multiplied with the constant $\frac{1}{4}$ (omitted in the equation above).

The item orientation towards the steepest slope is set by taking the arc cosine of the ratio between the $a_{il}$, i.e., the slope value of item $i$ on the coordinate axis $l$, and the $MDISC$ (Reckase, 2009, 1985).

$$
a_{il}= cos^{-1}\left(\frac{a_{il}}{\sqrt{\sum_{k=1}^m a^2_{ik}}}\right)
$$

The resulting direction vector is a characteristic of the item that describes the angular orientation of an item in a multidimensional latent trait space.

The multidimensional version of the difficulty parameter, here denoted $B$ as the DMIRT counterpart to the $b$-parameter in the unidimensional item response theory model, for item $i$, is defined as the negative intercept $d_i$ divided by the $MDISC$ (Reckase, 2009, 1985).

$$
MDIFF=B_i=\frac{-d_i}{\sqrt{\sum_{k=1}^m a^2_{ik}}}
$$

The $MDIFF$ is interpreted similarly as the difficulty parameter in the unidimensional model.
That is, higher values indicate that higher levels of ability for a probability of a correct response of more than .5 are necessary.
Moreover, the $MDIFF$, just as in the unidimensional model, sets the distance from the origin of the model to the point of inflection.
However, in DMIRT analysis, the $MDIFF$ becomes a multidimensional location parameter that indicates the distance from the origin to the point of the steepest slope following the direction vector given by the direction vector equation.

For Likert items that hold multiple item response functions, the $MDIFF$ will be turned into an index that indicates the distance from the origin to the point of inflection for all response functions derived from an item.
This, in turn, implies that the $MDIFF$ will show the *difficulty range* for an item in the model.

The $MDISC$ is visualized in DMIRT analysis by scaling the length of the vector arrows.
In brief, the bottom location coordinates of the vector arrows, given by the $MDIFF$ and direction vector, are multiplied with the $MDISC$ so that items with higher $MDISC$ have longer vector arrows (Reckase, 2009).
Accordingly, shorter vector arrows indicate lower discrimination (which in turn indicates an increased amount of model violations of the item model).

Lastly, because the $MDISC$ represents an item's maximum level of discrimination in the model it is a global parameter that cannot be used to compare item discrimination locally.
For the latter to be possible, the discrimination must be computed in a specified direction for the items.
This can be achieved with the $DDISC$, defined as follows (Reckase & McKinley, 1991).

::: {align="center"}
$DDISC = \sum_{k = 1}^{m} a_{ik} cos \alpha_{ik}$
:::

The $DDISC$ describes the level of discrimination for one or more items in the model at the angle set by the direction of choice.
Note, it is always true that $DDISC \leq MDISC$.

In the `D3mirt`package the $DDISC$ is computed for all items following the angle orientation given by the *construct vectors*.
Constructs, in this context, refer to the assumption that a subset of items can measure a higher-order latent variable.
In `D3mirt`, constructs are implemented as optional vectors whose orientation is calculated as the average direction, i.e., the average multidimensional discrimination of a subset of items in the model.
A construct vector will, therefore, point in the direction of the maximum slope of an imaginary item response function indicated by the items chosen by the user.

Item subsets for construct analysis are chosen by the user and can be exploratory (e.g., grouped based on observations) or theoretical (e.g., fixed a priori based on personality theory).
If constructs are used, the output will include reporting of the $DDISC$ parameter that shows how well the items discriminate under the assumption that they measure one of the constructs used in the analysis.
That is, while the $MDISC$ represents the maximum level of discrimination for the items in the model, the $DDISC$ represents the local discrimination that makes it possible to compare item discrimination in a specific direction set by the constructs.
Constructs are visually represented with construct vector arrows scaled to an arbitrary length.

## Limitations

The DMIRT method is currently limited to using the two-parameter compensatory models.
Regarding `D3mirt`, the number of dimensions is limited to three.
However, the number of dimensions need not be exactly three, but up to three.
This since only two items in the set are needed to identify the model (see the section on model identification below for more on the statistical requirements).

# Overview

The package includes the following functions.

-   `modid()`: D3mirt Model Identification
-   `D3mirt()`: 3D DMIRT Model Estimation
-   `summary()`: Summary Function for `D3mirt()`
-   `plotD3mirt()`: Graphical Output for `D3mirt()`

In what follows, the `D3mirt` procedure and some of its functions and options will be described using the built-in data set "anes0809offwaves".
The data set ($N = 1046, M_{age} = 51.33, SD = 14.56, 57\%$ Female) is a subset from the American National Election Survey (ANES) from the 2008-2009 Panel Study Off Wave Questionnaires, December 2009 (DeBell, et al, 2010; <https://electionstudies.org/data-center/2008-2009-panel-study/>).
All items measure moral preferences and are positively scored of Likert type, ranging from 1 = *Strongly Disagree* to 6 = *Strongly Agree*.
Demographic variables include age and gender (male/female).

The sections below are sorted under the following headings.

1.  Model Identification

-   1.1 The `modid()` Function
    -   Step 1: Explore the Data Structure
    -   Step 2: Item Selection
-   1.2 The Model Identification Procedure
-   1.3 Criteria For Model Identification
-   1.4 Limitations
-   1.3 Item Selection

2.  `D3mirt` Model Estimation

-   2.1 The `D3mirt()` Function
    -   Fitting the Compensatory Multidimensional Model
    -   The `D3mirt` Function Call
    -   Constructs

3.  Plotting

-   3.1 The `plotD3mirt()` Function
    -   Unidimensionality vs. Within-Dimensionality
    -   Model Violations
    -   Illustration: A Short Item and Dimensionality Analysis
    -   Other Graphical Options
        -   `items`
        -   `scale`
    -   `D3mirt` Profile Analysis

# 1. Model Identification

## The `modid()` Function

For the `D3mirt` analysis, two items with the following properties must be chosen to identify the compensatory model (Reckase, 2009).

The first item should not load on the second and third axes ($y$ and $z$), while the second item should not load on the third axis ($z$).
If this can be empirically achieved, it will be possible to create the orthogonal structure necessary for the analysis.
The `modid()` function can help by suggesting what items to use for this purpose.

Note, if improper items are chosen the model will be hard to interpret, or even unempirical if the data is forced on the model by compromising the necessary statistical requirements.
The `modid()` function was, therefore, developed to hinder the latter and to maximize the interpretive meaning by using an algorithmic approach.
Briefly, the function first order factors by the sum of squares and from this select the strongest loading items that meet the statistical assumptions described above.
This orders the model so that the strongest loading item, from the strongest factor, always aligns perfectly with the $x$-axis and that the other items follow thereon.
The model identification process is described in more detail below.

### Step 1: Explore the Data Structure

If the model is not known, the factor structure must be explored with exploratory factor analysis (EFA).
However, because `D3mirt` analysis is based on the M2PL and the MGRM, it is recommended to use multidimensional item response theory EFA methods, such as the EFA option in `mirt::mirt` (Chalmers, 2012) with `ìtemtype = 'graded'` or `'2PL'`, so that the EFA is performed with the proper item model.
Note, the EFA is only used to find model identification items that meet the necessary DMIRT model specification requirements.
The EFA model itself is discarded after this step in the procedure.
It user can therefore try different types of rotation methods and compare model identification results.
Note, because the EFA in the `mirt()` function takes a long time to perform, the item loadings from the EFA for this example are stored in the package file "efa.Rdata" and can be loaded in the next code chunk below.

```{r, message = FALSE, results = 'hide', eval = FALSE}
# Load data
data("anes0809offwaves")
x <- anes0809offwaves
x <- x[,3:22] # Remove columns for age and gender

# Fit a three-factor EFA model with the mirt package
e <- mirt::mirt(x, 3, itemtype = 'graded')

# Assign data frame with factor loadings with oblimin rotation
f <- summary(e, rotate= 'oblimin')
h <- data.frame(f$rotF)
```

### Step 2: Item Selection

The `modid()` takes in the factor solution from the EFA, assigned to a data frame $h$, and outputs an $S3$ object of class `modid` containing lists with data frames of estimates.
The most important is the item lists, (denoted `$id`), containing data frames that present suggestions on what items (`item.1`...`item.n`) to use for the model identification.
The data frames have one column for the loadings from each item on the factor of interest, and one column with absolute sum scores (denoted `ABS`) for each item calculated from the remaining factor loadings in the model.
Each item list is sorted with the lowest absolute sum score highest up.
Consequently, the top items in each list are the items that best meet the necessary statistical requirements for model identification.
Therefore, for a three-dimensional model, all else equal, the item highest up in the first list should be used to identify the $x$-axis, and the item highest up in the second list should be used to identify the $y$-axis, and so on.

```{r}
# Optional: Load the EFA data for this example directly from the package file
load("efa.Rdata")

# Call to modid()
modid(h)
```

As can be seen, the first item, that will be used to identify the $x$-axis, is found in the first list, `id[[1]]` and `item.1`.
In this case, the best item for the $x$-axis is item "W7Q3".
The item that identifies the $y$-axis is found in the next list, `id[[2]]` and `Item.2`.
In this case, the best item for the $y$-axis is item "W7Q20".

Sometimes, however, the model is hard to identify.
If this happens, try the following in the order suggested.
For more on the function arguments see the section below regarding the model identification procedure.

1.  Change the rotation method in the EFA, e.g., to change from *oblimin* to *varimax*.
2.  Adjust the `lower` bound in `modid()`.
3.  Override factor order with `fac.order`.
4.  Adjust the `upper` bound in `modid()`.

The latter (point 4) should, however, only be used as a last resort.
This is because the upper bound sets the upper limit for item inclusion.
Adjusting this limit too high means that the necessary statistical requirements are compromised.
The lower limit (point 2), however, only increases the size of the item pool used for the item selection.
It is, therefore, recommended to adjust the lower limit up and down to see if the output differs, and from that make the final decision.

```{r}
# Call to modid with increased lower and higher bound
modid(h, lower = 1, upper = .12 )
```

In this case, the same items are suggested even after adjusting both the `lower` and `upper` bounds.

Another option (point 3) is to override the factor order with the `fac.order` argument.
More specifically, `modid` orders factor by squared factor loadings so that the strongest factor is used first, the second strongest factor is used second, and so on.
Sometimes, however, there is only a very small difference between the squared factor loadings that in turn can cause problems (often only observable at later stages) when trying to find the best items for the model identification.
In such situations, it can be useful to rearrange the factor order manually to see if the model solution improves.

Since the squared factor loadings for factors 2 and 3 in this example are somewhat similar, it could be useful to compare the results.
The latter is, however, outside of the scope of this vignette.

```{r}
# Override factor order by reversing columns in the original data frame
modid(h, fac.order = c(3, 2, 1))
```

In this case, we find the item that was previously suggested for the $y$-axis, is now suggested for the $x$-axis.
For the $y$-axis, we find a new item, "W7Q13", suggested to identify the $y$-axis.

## The Model Identification Procedure

The `modid()` function uses an iterating algorithmic procedure that can be user adjusted.
In brief, in the default automatic mode, `modid()` starts by first calculating the sum of squares loadings on all factors $F$ in the data frame $x$ and then rearranging the columns in $x$, in decreasing order following the level of strength of the sum of squares loadings.
Next, the function creates a list containing the factor loadings on the first factor, $f_1$, and absolute sum scores of the factor loadings on the remaining factors, i.e., $F-f_1$, row-wise.
The list is rearranged in decreasing order based row-wise on factor loading strength on $f_1$.

Next, items are selected by first scaling $f_1$ loadings and then extracting the items with the highest loadings on $f_1$, up to a standard deviation of $0.5$ (the default setting) as the lower bound criteria counting from the top.
That is, rows with raw factor scores and absolute sum scores are extracted until the lower bound for factor loadings on $f_1$ is reached.
This allows the function to extract more rows in the case empirical factor loadings are very similar in strength.
The result is recorded as a nested list before the function starts over with the next factor, $f_2$, and so on.

For every iteration, the algorithm jumps to the next factor in the EFA model, rearranges rows, and extracts the strongest loading items.
However the absolute sum score is always assessed based on the number of factors less than the total number of factors, following the order of iteration, That is, iteration $1$ use factor loadings from all factors $F-f_1$, iteration $2$ $F-(f_{1,2})$, iteration $3$ $F-(f_{1,2,3})$, and so on, when calculating the absolute sum scores.

## Criteria For Model Identification

Model identification items should preferably (a) have an absolute sum score of $\leq .10$ and (b) have the highest factor loading scores on the factor of interest.
Of these two criteria, (a) should be given the strongest weight in the selection decision.
If these conditions cannot be met, the user is advised to proceed with caution since the loading scores, therefore, imply that an adequate orthogonal structure may not be empirically attainable.
If problems in the model identification process occur, please follow the advice given above.

## Limitations

The `modid()` function is not limited to three-dimensional analysis and can be used on any number of dimensions.
Although based on suggestions on model identification given by Reckase (2009) for this type of analysis, the function offers some expansions that introduce more precision.
The latter foremost consists in incorporating the sum of squares and factor loadings in the item selection process (unless the user has not specified otherwise).
Experience tells us that this is good practice that often leads to better results compared to other known options.
However, it is important to recognize that the model identification procedure only gives suggestions to the model specification, and there could be situations where the researcher should consider other methods.
Note, that two items can be found to identify the model do not imply successful outcomes when using this methodology (i.e., that the model is *good*).
But it does suggest that the methodology *can* be used and the results will be possible to interpret in a meaningful way.

# 2. D3mirt model estimation

## The `D3mirt()` Function

The `D3mirt()` function takes in a data frame with model parameters from a three-dimensional compensatory model and returns an $S3$ object of class `D3mirt` with lists of $a$ and $d$, $MDISC$, and $MDIFF$ parameters, direction cosines, and spherical coordinates.
Regarding the latter, spherical coordinates are represented by $\theta$ and $\phi$.
The $\theta$ coordinate is the positive or negative angle in degrees, starting from the $x$-axis, of the vector projections from the vector arrows in the $xz$-plane up to $\pm 180°$.
Note, the $\theta$ angle is oriented following the positive pole of the $x$ and $z$ axis so that the angle increases clockwise in the graphical output.
The $\phi$ coordinate is the positive angle in degrees from the $y$-axis and the vectors.
Note, the $\rho$ coordinate from the spherical coordinate system is in DMIRT represented by the $MDIFF$, and so is reported separately.

If constructs are used, the function also returns construct direction cosines, spherical coordinates for the construct vector arrows, and $DDISC$ parameters (one index per construct).

### Fitting the Compensatory Multidimensional Model

The three-dimensional compensatory model is specified so that all items load on all three factors in the model, and all factors are constrained to be orthogonal (see below).
The fitting of the model is preferably done with the `mirt::mirt` (Chalmers, 2012) function.
Observe that the START and FIXED commands are used to fix the slope parameters on the second, $a2$, and third, $a3$.
factor for item $_1$ (W7Q3), and the slope on the third, $a3$, factor for item $i_2$ (W7Q20).
Note, because the fitting of the compensatory model in the `mirt()` function takes a long time to fit, the item parameters are available in the package file "d.Rdata" and can be loaded in the next code chunk below.

```{r, message = FALSE, results = 'hide', eval = FALSE}
# Load data
data("anes0809offwaves")
x <- anes0809offwaves
x <- x[,3:22] # Remove columns for age and gender

# Fit a three-dimensional graded response model with orthogonal factors
# Example below uses Likert items from the built-in data set "anes0809offwaves"
# Item W7Q3 and item W7Q20 was selected with `modid()`
# The model specification set all items in the data set (1-20) 
# to load on all three factors (F1-F3)
# The START and FIXED commands are used on the two items to identify the DMIRT model
 spec <- ' F1 = 1-20
           F2 = 1-20
           F3 = 1-20

           START=(W7Q3,a2,0)
           START=(W7Q3,a3,0)

           START=(W7Q20,a3,0)

           FIXED=(W7Q3,a2)
           FIXED=(W7Q3,a3)

           FIXED=(W7Q20,a3) '


mod1 <- mirt::mirt(x, 
                   spec, 
                   itemtype = 'graded', 
                   SE = TRUE, 
                   method = 'QMCEM')
 
# Assign a data frame with factor loadings (located in the first three columns in mod1),
# and difficulty parameters (columns 4-8 in mod1) with mirt::coef and $'items'[,1:8]))
d <- data.frame(mirt::coef(mod1, 
                           simplify=TRUE)$'items'[,1:8])
```

### The `D3mirt()` Function Call

The `D3mirt()` function call is straightforward.
The output, however, is lengthy so the use of the generic summary function, included in the package, when inspecting the results is recommended.

```{r}
# Optional: Load data frame d for for this example directly from the package file
load("d.Rdata")

# Call D3mirt() 
g <- D3mirt(d)
summary(g) # Show summary of results
```

As can be seen, the output from the summary function starts by reporting the number of items and difficulty levels.
If constructs were used, the output will also include statements on what items belong to which construct (see example below).
Next, the factor loadings and the difficulty parameters from the compensatory model are reported followed by all necessary DMIRT estimates.
Examples of how DMIRT estimates can be used when reporting results are given below in the item and dimensionality analysis example.

### Constructs

Constructs can be included in the analysis by creating one or more nested lists that indicate what items belong to what construct.
From this, the `D3mirt()` function finds the average direction of the subset of items contained in each construct list, by adding and normalizing the direction cosines for the items and scaling the construct direction vector to an arbitrary length.
Note, the length of the construct vector arrows can be user adjusted.

The construct vector arrows can contribute to the analysis by (a) visualizing the average direction for a subset set of items, and (b) showing how all items discriminate locally in the direction of the construct vector with the help of the $DDISC$ index.

The constructs included below were grouped based on exploratory reasons, i.e., because these items cluster in the model (will be observable in the graphical output).

```{r}
# Call to D3mirt(), including optional nested lists for three constructs
# Item W7Q16 is not included in any construct because of model violations
# The model violations for the W7Q16 item can be seen when plotting the model
c <- list(list (1,2,3,4), 
          list(5,7,8,9,10), 
          list(11,12,13,14,15,15,16,17,18,19,20))
g <- D3mirt(d, c)
summary(g)
```

Compared to the previous function call to `D3mirt()`, we now see two extra frames: one frame with direction cosines ($D.Cos X, D.Cos Y, D.Cos Z$) and spherical coordinates ($\theta, \phi$) for the constructs, and one frame with the $DDISC$ estimates, containing the $DDISC_{1,2,3}$ parameters for the items corresponding to the three constructs (1,2,3) (assigned with *c* in the example above).

# 3. Plotting

## The `plotD3mirt()` Function

The `plotD3mirt` function is built on the `rgl` package (Adler & Murdoch, 2023) for visualization with OpenGL.
The output consists of a three-dimensional interactive RGL device, displaying vector arrows with the latent dimensions running along the orthogonal axes centered at zero.
If polytomous items are used each item will have multiple arrows, representing the multiple item step response functions, running along the exact same direction in the model.

### Model Violations

When plotting the `D3mirt` model with `plotD3mirt()`, it is possible to visually observe statistical violations in the graphical output returned.
For instance, shorter vector arrows indicate weaker discrimination and therefore also higher amounts of model violations.
As another example, if an item struggles or even fail to describe any of the latent variables in the model, it can often lead to an extreme stretch of the $MDIFF$ range.
This is comparable to trace lines turning horizontal in a unidimensional item response theory model.
Some examples of model violations and within-dimensionality will be given in the illustration below.

### Illustration: A Short Item and Dimensionality Analysis

To illustrate the utility of `D3mirt` visualization, a short example using the `anes0809offwaves` data set will be presented.
Graphing in default mode by calling `plotd3mirt()` will return an RGL device that will appear in an external window as a three-dimensional interactive object that can be rotated manually by the user.
In this illustration, however, all RGL devices are plotted as inline interactive objects with the help of R markdown.
Note, the `view` argument is used in all function calls to `plotD3mirt()` below.
This was only done for optimizing the size of the RGL device (the default is `view = c(15, 20, 7)`) when creating this R Markdown vignette.

```{r, testg1, webgl = TRUE, fig.width = 7, fig.height = 7}
# Plot RGL device
plotD3mirt(g, view = c(15, 20, 0.6))
```

An example of how the output can be described could be the following.

> As can be seen in the figure, the pattern in the data indicates the presence of foremost two main latent constructs indicated by the items, one aligned with the $x$-axis and one approaching the $y$-axis.
> We might also suspect the presence of a third construct located close to the $xy$-plane, between the $x$ and $z$ axes.
> Studying the content of the items, the labels *Compassion*, *Conformity*, and *Fairness* were introduced.

To get a better understanding of the interrelation of the data, constructs can be added to asses the average angle when grouping items.
As mentioned above, in this example the items have been grouped in constructs in an exploratory fashion, i.e., based on their observed location in the model.
Note, item W7Q16 was not included in any of the constructs because of a high amount of model violation tendencies and notable within-multidimensionality.

To plot constructs alongside item vectors, change to `constructs = TRUE`.
The constructs can be named with strings as input to the `construct.lab` argument.
In this example, construct labels were chosen based on item content.

```{r, testg3, webgl=TRUE, fig.width = 7, fig.height = 7}
# Plot RGL device with constructs visible and named
plotD3mirt(g, 
           constructs = TRUE, 
           construct.lab = c("Fairness", "Conformity", "Compassion"), 
           view = c(15, 20, 0.6))
```

An example of how the output can be described could be as follows.

> The angles of the constructs inform us that Compassion ($\theta = 1.710^{\circ}$, $\phi = 86.486^{\circ}$) and Conformity ($\theta = - 2.519^{\circ}$,$\phi = 28.192^{\circ}$) have some within-multidimensional tendencies.
> However, they are both more or less orthogonal to the $z$-axis ($\theta = 1.710^{\circ}$ and $\theta = -2.519^{\circ}$ respectively).
> Next, we find Fairness ($\theta = 49.106^{\circ}$, $\phi = 78.308^{\circ}$) with clear within-multidimensional tendencies with respect to the $x$-axis.
> Thus, the output indicates that Compassion and Conformity could be independent constructs but that Fairness seems not to be.

As was mentioned above, the W7Q16 had the most measurement problems of all items in the data.
Foremost, the short vector arrows indicate high amounts of model violations.
Moreover, the location of the item in the model also indicates that the item is within-multidimensional and that it does not seem to belong to any construct explicitly.

The `plotD3mirt()` function allows plotting W7Q16 alone using argument `items` and by entering the number indicating where the item appears in the data set (see `?anes0809offwaves`).

```{r, testg4, webgl=TRUE, fig.width = 7, fig.height = 7}
# Item W7Q16 has location 6 in the data set (gender and age excluded)
# The item is plotted together with constructs to aid the visual interpretation
plotD3mirt(g, 
           constructs = TRUE, 
           items = 6, 
           construct.lab = c("Fairness", "Conformity", "Compassion"), 
           view = c(15, 20, 0.6))
```

An example of how the output can be described could be as follows.

> The figure shows that item W7Q16 is located at $\theta = 16.083^{\circ}$, $\phi = 57.473^{\circ}$, indicating that the item is within-multidimensional with respect to the $x$ and $y$-axis; but much less so with respect to the $z$-axis.
> In addition, the directional discrimination further underscores that the item does not seem to measure any particular construct ($DDISC_1 = .656$, $DDISC_2 = .656$, $DDISC_3 = .617$).
> The global discrimination ($MDISC = .770$, $MDIFF_{range} = [-4.838, 2.349]$) is also the lowest of all discrimination scores in the model.
> This, combined, implies that the item in question does not seem to fit the three-dimensional DMIRT used in this analysis and should therefore be removed or adapted.
> On a side note, we can also note that item W7Q15, $MDISC = .923$, $MDIFF_{range} = [-4.680, 1.051]$) has the second lowest global discrimination score.
> However, this item does seem to belong to the Conformity construct, observable when comparing angle orientation ($\theta = -19.436^{\circ}, \phi = 31.516^{\circ}$) and discrimination ($MDISC = .923$, $DDISC_1 = .332$, $DDISC_2 = .912$, $DDISC_3 = .497$).

### Other Graphical Options

#### `diff.level`

The user has the option of plotting on one level of difficulty at a time with the `diff.level` argument on the entire scale, a subset of items or on one item at a time.
Note, *difficulty* refers to the number of item response functions, i.e., the total number of response options minus one.
In this case, $6$ response options were used which means that the model has $5$ levels of difficulty.

```{r, testg5, webgl = TRUE, fig.width = 7, fig.height = 7}
# Plot RGL device on item difficulty level 5
plotD3mirt(g, 
           diff.level = 5, 
           view = c(15, 20, 0.6))
```

### `items`

A subset of items can be plotted for a more thorough investigation.
In the example below constructs are kept in the function call which can help with the visual interpretation of the item subset.
Items are selected, just as in the single case, based on the item order in the original data frame (see `?anes0809offwaves`)

```{r, testg6, webgl=TRUE, fig.width = 7, fig.height = 7}
# A selection of Conformity items from the model plotted with constructs
plotD3mirt(g, 
           constructs = TRUE, 
           items = c(5,7,8,9,10), 
           construct.lab = c("Fairness", "Conformity", "Compassion"), 
           view = c(15, 20, 0.6))
```

#### `scale`

The `D3mirt()` function returns item vector coordinates estimated with and without the $MDISC$ as a scalar for the arrow length.
When the $MDISC$ is not used for the arrow length, all item vector arrows are scaled to one unit length.
This allows the user to graph the item vector arrows with `plotD3mirt()` set to uniform length.
This can help reduce visual clutter in the graphical output.
To view the item vector arrows without the $MDISC$, set `scale = TRUE`.

```{r, testg7, webgl=TRUE, fig.width = 7, fig.height = 7}
# Plot RGL device with items in uniform length and constructs visible and named
plotD3mirt(g, 
           scale = TRUE, 
           constructs = TRUE, 
           construct.lab = c("Fairness", "Conformity", "Compassion"), 
           view = c(15, 20, 0.6))
```

## `D3mirt` Profile Analysis

The `plotD3mirt()` function can also display respondents in the three-dimensional model represented as spheres located using respondent factors scores used as coordinates.
This allows for a profile analysis in which respondents can be separated, or subset, conditioned on single or multiple criteria and then plotted.
The resulting output shows where the respondents are located in the model, and, accordingly, what model profile best describes them.
Similarly, respondent categories can be simultaneously compared to see if a group-level effect can be visually observed.

To do this, the user must first extract respondent factor scores with `mirt::fscores` (Chalmers, 2012) and then seprate or select a subset of respondent rows based on one or more criteria.
The resulting data frame is imputed in the `profiles` argument.
Generally, it can be useful to hide vector arrows with `hide = TRUE` when plotting respondent profiles to avoid visual cluttering.
The example below separates respondents using the gender variable included in the built-in data set.
To save some time in running the examples, the `fscores()`output is stored in the package file "fscores.Rdata" and can be loaded in the next code chunk below.

```{r, eval = FALSE}
# Extract respondent factor scores from mod1 with fscores() function from [mirt::mirt]
f <- mirt::fscores(mod1, 
                   method="EAP", 
                   full.scores = TRUE, 
                   full.scores.SE = FALSE, QMC = TRUE)
```

```{r}
# Optional: Load respondent factor scores for this example directly from the package file
load("fscores.Rdata")

# Attach f to the gender variable (column 2 from anes0809offwaves data set; "W3XGENDER")
# Use cbind with fscores() output attached first
data("anes0809offwaves")
x <- anes0809offwaves
z <- data.frame(cbind(f, x[,2]))
```

The `plotD3mirt` function uses `as.factor()` to count the number of factor levels in the data imputed in the `levels` argument.
This means that raw data can be used as is but the number of colors in the color vectors argument (`sphere.col`) may need to be adapted.
In the example below, the criteria variable for gender only hold two factor levels and therefore only two colors in the color vector are needed.

Call `plotD3mirt` with the respondent data frame $z$ in the `profiles` argument and the `levels` argument with the levels column subset from $z$.
In the function call below, the axes in the model are named using the `x.lab`, `y.lab`, and `z.lab` arguments following the direction of the constructs.
Note, the model axes represent unidimensional singular structures, or traits, in this case borrowing the names of the constructs.

```{r, testg8, webgl=TRUE, fig.width = 7, fig.height = 7}
# Plot profiles with item vector arrows hidden
# Score levels: 1 = Blue ("male") and 2 = Red ("female")
plotD3mirt(g, hide = TRUE, 
           profiles = z, 
           levels = z[,4], 
           sphere.col = c("blue", "red"), 
           x.lab = "Compassion", 
           y.lab="Conformity", 
           z.lab="Fairness", 
           view = c(16, 20, 0.6))
```

An example of how the output can be described could be as follows.

> In the figure, it can be observed a simple profile on gender in which more women tend to have higher levels of trait Compassion.
> When rotating the model $90^{\circ}$ clockwise, there seems not to be any easily observable gender difference related to trait Conformity or trait Fairness.

The use of `rep()` function makes it possible to create groups based on factor levels.
This can be useful when a criterion variable has a wide data range, such as an age variable.
More specifically, a color vector for the `sphere.col` argument can be created with color names repeated by `rep()`.
When plotting, the `plotD3mirt()` function will pick colors from the `sphere.col` argument following the factor order in the `levels` argument.
The example below illustrates this when comparing respondents 30 years or younger against 70 years or older.

First, we must count the number of factor levels in the variable.
This can be done with, the `nlevels(as.factor(x))`.
Then we use the output from the latter to set the appropriate size of color vector for `sphere.col`.

```{r}
# Column bind fscores() with age variable ("W3Xage")
y <- data.frame(cbind(f, x[,1]))

# Subset data frame y conditioned on age <= 30
z1 <- subset(y, y[,4] <= 30)

# Subset data frame y conditioned on age >= 70
z2 <- subset(y, y[,4] >= 70)

# Row bind z1 and z2
z <- rbind(z1,z2)

# Check number of factor levels with nlevels() and as.factor()
nlevels(as.factor(z1[,4]))
nlevels(as.factor(z2[,4]))

# Use rep() to create a color vector to color groups based on the nlevels() output
# z1 has 14 factor levels and z2 has 16 factor levels
# z1 respondents are colored red and z2 are colored blue
colvec <- c(rep("red", 14), 
            rep("blue", 16))
```

```{r, testg9, webgl=TRUE, fig.width = 7, fig.height = 7}
# Call plotD3mirt with profile data on age with item vector arrows hidden
plotD3mirt(g, hide = TRUE, 
           profiles = z, 
           levels = z[,4], 
           sphere.col = colvec, 
           x.lab = "Compassion", 
           y.lab="Conformity", 
           z.lab="Fairness", 
           view = c(15, 20, 0.6))
```

An example of how the output can be described could be as follows.

> As can be seen, the figure indicates an age effect in which older individuals have higher levels of trait Conformity.
> Rotating the model to the left also shows that older individuals may have slightly higher levels of trait Fairness, even if the effect is less clear.
> There does not seem to be any difference in trait Compassion, however.
> To sum, we can say, therefore, that the analysis indicates a possibility that older individuals may have a moral profile consisting of high trait Conformity and possibly also high trait Fairness.

It is also possible to plot a confidence interval in the shape of an ellipse surrounding the individual factor scores.
In the example below, the younger individuals ($\leq30$) are selected and plotted with a $95\%$ *CI*.

```{r}
# Column bind fscores() with age variable ("W3Xage")
y <- data.frame(cbind(f, x[,1]))

# Subset data frame y conditioned on age <= 30
z1 <- subset(y, y[,4] <= 30)

# Use rep() to create a color vector to color groups based on the nlevels() output
# z1 has 14 factor levels
colvec <- c(rep("red", 14))
```

To plot the *CI*, the `ci` argument is set to `TRUE`.
The color of the sphere was also changed from the default `grey80` to `orange` in the example below.
Note, the *CI* limit can be adjusted with the `ci.level` argument.

```{r, testg10, webgl=TRUE, fig.width = 7, fig.height = 7}
# Call plotD3mirt with profile data on age with item vector arrows hidden
plotD3mirt(g, hide = TRUE, 
           profiles = z1, 
           levels = z1[,4], 
           sphere.col = colvec, 
           x.lab = "Compassion", 
           y.lab="Conformity", 
           z.lab="Fairness", 
           ci = TRUE, 
           ci.level = 0.95, 
           ellipse.col = "orange",
           view = c(15, 20, 0.6))
```

An example of how the output can be described could be as follows.

> In Figures 7 and 8 we can see a tendency for a profile on age in which younger individuals could be described as less oriented towards trait Conformity.
> We can also observe a tendency for what could be an interaction effect in which higher levels of trait Conformity seem to be associated with lower levels of trait Fairness.

# Exporting The RGL Device

Some options for exporting the RGL device are shown below.
Over and above these, it is also possible to export graphical devices in R Markdown documents with `rgl::hookwebgl()` together with graphical options for knitr, as was done when creating this vignette.

```{r, eval = FALSE}
# Export an open RGL device to the console that can be saved as a html or image file
plotD3mirt(g, 
           constructs = TRUE)
s <- scene3d()
rgl::rglwidget(s, 
               width = 1040, 
               height = 1040)

# Store widget directly to file
plotD3mirt(g, 
           constructs = TRUE)
s <- scene3d()
htmlwidgets::saveWidget(rglwidget(s, 
                        width = 1040, height = 1040), 
                        file = "anes0809offwaves.html", 
                        libdir = "libs", 
                        selfcontained = FALSE)
```

```{r, eval = FALSE}
# Export a snap shoot of an open RGL device directly to file
plotD3mirt(g, 
           constructs = TRUE)
rgl::rgl.snapshot('RGLdevice.png', 
                    fmt = 'png')
```

# References

Adler, D., & Murdoch, D.
(2023).
*Rgl: 3d Visualization Using OpenGL* [Computer software].
<https://dmurdoch.github.io/rgl/index.html>

Chalmers, R., P. (2012).
mirt: A Multidimensional Item Response Theory Package for the R Environment.
*Journal of Statistical Software, 48*(6), 1-29.
<https://doi.org/10.18637/jss.v048.i06>

DeBell, M., Krosnick, J. A., & Lupia, A.(2010). *Methodology Report and User's Guide for the 2008-2009 ANES Panel Study*.
Palo Alto, CA, and Ann Arbor, MI: Stanford University and the University of Michigan.

Muraki, E., & Carlson, J. E.
(1995).
Full-Information Factor Analysis for Polytomous Item Responses.
*Applied Psychological Measurement, 19*(1), 73-90.
<https://doi.org/10.1177/014662169501900109>

Reckase, M. D.(2009).*Multidimensional Item Response Theory*.Springer.
<https://doi.org/10.1007/978-0-387-89976-3>

Reckase, M. D.(1985). The Difficulty of Test Items That Measure More Than One Ability.
*Applied Psychological Measurement, 9*(4),401-412.
<https://doi.org/10.1177/014662168500900409>

Reckase, M. D., & McKinley, R. L.
(1991).
The Discriminating Power of Items That Measure More Than One Dimension.
*Applied Psychological Measurement, 15*(4), 361-373.
<https://doi.org/10.1177/014662169101500407>
