Skip to contents

Exploratory factor analysis (EFA) for repeated-measures data, such as an ESM/EMA questionnaire answered many times by each participant.

The factor model is fitted as a mixed model (via glmmTMB). Each grouping variable listed in random gets item-specific random intercepts (e.g., each participant's own average on each item, with an unstructured covariance between items). The factors then describe how the items co-fluctuate around those averages, i.e., the within-level structure. The result is a single set of loadings, interpreted like a regular EFA.

With random = NULL, the model reduces to a standard maximum-likelihood EFA (the same model as stats::factanal() or psych::fa(fm = "ml")).

Usage

fa_multilevel(
  data,
  nfactors = 1,
  random = NULL,
  rotate = "oblimin",
  items = NULL,
  scores = TRUE,
  verbose = TRUE,
  ...
)

Arguments

data

A data frame with one row per observation (e.g., one ESM prompt), item columns, and the grouping column(s) used in random.

nfactors

[integer: 1]
Number of factors. If several values are given (e.g., 1:4), each solution is fitted and compared (see Value).

random

[formula or NULL: NULL]
One-sided formula of random intercepts, e.g. ~ (1 | Participant). Only intercepts are supported ((1 | group)), possibly crossed or nested. NULL fits a standard (single-level) EFA.

rotate

[character(1): "oblimin"]
Rotation method: "none", "varimax", "promax", or one of the GPArotation methods "oblimin", "quartimin", "geominQ", "geominT", "bentlerQ", "bentlerT", "simplimax", "quartimax", "equamax", "infomaxQ", "infomaxT", "bifactorQ", "bifactorT".

items

[character or NULL: NULL]
Names of the item columns. If NULL, all numeric columns except the grouping variables are used.

scores

[logical(1): TRUE]
Whether to compute factor scores.

verbose

[logical(1): TRUE]
Print progress messages.

...

Additional arguments passed to glmmTMB::glmmTMB() (e.g., control).

Value

With a single value of nfactors, an object of class experdyn_fa_multilevel — a named list with:

ElementDescription
loadingsStandardised, rotated loadings (items × factors; class loadings).
PhiFactor correlation matrix.
communalityWithin-level communalities (h2).
uniquenessesWithin-level uniquenesses (u2 = 1 - h2).
varianceData frame decomposing each item's total variance into the share due to each grouping variable, the factors, and the residual.
scoresdata with the item columns replaced by factor scores (conditional modes, analogous to regression scores); NULL if scores = FALSE.
fit_indicesNamed vector with logLik, df (number of parameters), AIC, BIC (based on the number of observations). The log-likelihood is reported even when the Hessian is not positive definite (where stats::logLik() on the glmmTMB model returns NA).
convergedWhether the optimiser converged.
pd_hessianWhether the Hessian is positive definite. FALSE often means that a variance is estimated at zero (e.g., an item with no differences between groups); the loadings can still be usable.
modelThe underlying glmmTMB model.
items, nfactors, rotate, random, groups, n_obs, n_groupsSettings and sample sizes.

With several values of nfactors, an object of class experdyn_fa_multilevel_comparison — a named list with:

ElementDescription
performanceData frame with one row per solution (printed by default): Factors, Parameters, logLik, AIC, BIC, Delta_BIC (difference from the lowest BIC), BIC_weight (relative support for each solution, summing to 1), Explained (proportion of the within-level item variance explained by the factors) and Converged.
bestThe solution with the lowest BIC among the converged ones (an experdyn_fa_multilevel object). If no solution has a valid BIC, the solution with the fewest factors (preferring converged ones), with a warning.
solutionsList of all successfully fitted solutions, named n followed by their number of factors (e.g., $solutions$n3 for the 3-factor solution).

Details

Model. Items are reshaped to long format and modelled as value ~ 0 + item + (0 + item | group) + rr(0 + item | observation, d = nfactors), with one residual variance per item. The reduced-rank rr() term is the factor model: each observation (row of data) has nfactors latent scores that load on the items. Each (1 | group) in random adds a (0 + item | group) term, absorbing stable differences between groups. Several grouping variables can be combined, crossed (~ (1 | Participant) + (1 | Day)) or nested (~ (1 | Site/Participant)).

Loadings are standardised relative to the observation-level (within) variance of each item, then rotated with GPArotation (10 random starts, to avoid local optima). Varimax uses Kaiser normalisation, like stats::varimax(); promax is computed from that varimax solution, like stats::promax(). With a single grouping variable and many observations per group, the loadings are close to those of an EFA run on person-mean-centred data.

Missing data. Item-level missing values are handled by full-information maximum likelihood (all available responses are used). Rows where all items are missing are excluded and get NA factor scores.

Choosing the number of factors. The model has a proper likelihood, so solutions with different numbers of factors can be compared with information criteria. Passing a vector to nfactors (e.g., 1:4) fits all of them and returns a comparison (see Value); the best solution is the one with the lowest BIC. The BIC uses the number of observations (rows of data), as in standard factor analysis, rather than the number of item responses (which glmmTMB::glmmTMB() would count, over-penalising additional factors). The AIC is also reported, but it tends to favour too many factors in large samples. A solution that fails with an error is dropped from the comparison with a warning, and solutions that did not converge are only chosen as best if none of them converged.

Recommended use in experdyn. Run fa_multilevel() on the raw data, before resample_timeseries(): interpolated data would artificially inflate the sample size. The $scores data frame keeps the original non-item columns (participant, timestamp, ...), so it can be passed directly to resample_timeseries().

Number of groups. Each grouping variable gets an unstructured item covariance matrix (p(p + 1) / 2 parameters for p items), which needs enough groups to be estimated. Grouping variables with few levels (e.g., fewer than a few times the number of items) may fail to converge.

Limitations. Items are treated as continuous (Gaussian). Autocorrelation between successive observations is not modelled: loadings remain unbiased, but the model treats observations as exchangeable within each group, so no standard errors are reported. Fitting can take a minute or more for large datasets.

See also

resample_timeseries() to process the factor scores further. model_parameters() to get the loadings as a parameters table, which can be plotted with see and processed like the output of parameters::factor_analysis().

Examples

# \donttest{
if (requireNamespace("glmmTMB", quietly = TRUE) &&
    requireNamespace("GPArotation", quietly = TRUE)) {
    # 30 participants x 30 prompts, 6 items, 2 within-person factors
    set.seed(1)
    L <- cbind(c(.8, .7, .6, 0, 0, 0), c(0, 0, 0, .8, .7, .6))
    d <- do.call(rbind, lapply(1:30, function(i) {
        f <- matrix(rnorm(30 * 2), 30, 2)
        y <- f %*% t(L) + matrix(rnorm(30 * 6, sd = .6), 30, 6)
        y <- sweep(y, 2, rnorm(6, sd = .7), `+`) # participant's own averages
        data.frame(Participant = i, Prompt = 1:30, y)
    }))

    efa <- fa_multilevel(
        d,
        nfactors = 2,
        random = ~ (1 | Participant),
        items = paste0("X", 1:6)
    )
    efa
    head(efa$scores)
}
#> Fitting the factor model with glmmTMB (may take a while)...
#> Done in 5.1 seconds.
#>   Participant Prompt          F1         F2
#> 1           1      1  0.80337441  0.0221792
#> 2           1      2  0.04801586  0.6121435
#> 3           1      3  0.06353698 -0.2377482
#> 4           1      4 -0.99414379  1.4109547
#> 5           1      5 -1.36422762  0.3557540
#> 6           1      6 -0.53137200 -0.3702923
# }