Skip to contents

Imagine you have a dataset containing the answers of 30 participants who, for 8 days, received 5 notifications a day asking them how happy, cheerful, content, sad, energetic, alert, active and tired they felt, on sliders from 0 to 100.

That is 8 time series per participant. Before studying their dynamics (e.g., with make_statespace() and compute_rqa()), you probably want to summarise these items with a few underlying dimensions, such as valence and arousal. Fewer dimensions make state-space reconstructions simpler and avoid the curse of dimensionality: in a space with many dimensions, states are rarely close to each other, and recurrence or entropy measures break down.

Factor analysis is the natural tool for this, but there is a catch: the observations are nested within participants. Items can go together for two different reasons:

  • Within-person (moment to moment): when someone feels happier than usual, they also tend to feel more cheerful than usual.
  • Between-person (stable differences): some people are, on average, happier and more energetic than others.

A regular factor analysis mixes both. fa_multilevel() separates them by fitting the factor analysis as a mixed model.

The data

We simulate the dataset described above. In the simulation, the moment-to-moment answers are driven by two correlated dimensions (valence and arousal, with a correlation of .30), whereas the stable differences between participants follow a single “general well-being” dimension.

Show the simulation code
set.seed(3)
n_participants <- 30
n_days <- 8
prompts_per_day <- 5
items <- c("Happy", "Cheerful", "Content", "Sad", "Energetic", "Alert", "Active", "Tired")

# Moment-to-moment structure: two correlated dimensions, valence and arousal
loadings_within <- cbind(
    Valence = c(0.8, 0.8, 0.7, -0.7, 0, 0, 0, 0),
    Arousal = c(0, 0, 0, 0, 0.6, 0.6, 0.5, -0.6)
)
# Stable differences between people: one general "well-being" dimension
loadings_between <- c(0.6, 0.6, 0.5, -0.5, 0.5, 0.5, 0.4, -0.4)
item_means <- c(60, 55, 60, 30, 50, 55, 45, 40)

simulate_participant <- function(id) {
    n <- n_days * prompts_per_day
    # Momentary valence and arousal: correlated (r = .30) and carrying over
    # from one prompt to the next (autocorrelation of .50)
    shocks <- matrix(rnorm(n * 2), n, 2) %*% chol(matrix(c(1, .3, .3, 1), 2))
    states <- shocks
    for (t in 2:n) {
        states[t, ] <- 0.5 * states[t - 1, ] + sqrt(1 - 0.5^2) * shocks[t, ]
    }
    # This participant's own average on each item
    person <- loadings_between * rnorm(1) + rnorm(8, sd = 0.3)
    y <- states %*% t(loadings_within) + matrix(rnorm(n * 8, sd = 0.5), n, 8)
    y <- sweep(y, 2, person, "+")
    # Answers on 0-100 sliders
    y <- sweep(15 * y, 2, item_means, "+")
    y <- round(pmin(pmax(y, 0), 100))
    colnames(y) <- items
    # 5 prompts a day, around 9:00, 12:00, 15:00, 18:00 and 21:00
    times <- as.POSIXct("2025-03-03 09:00", tz = "UTC") +
        rep(0:(n_days - 1), each = prompts_per_day) * 86400 +
        rep(seq(0, 12, by = 3), times = n_days) * 3600 +
        round(runif(n, -1800, 1800))
    data.frame(Participant = sprintf("P%02d", id), Time = times, y)
}

data <- do.call(rbind, lapply(seq_len(n_participants), simulate_participant))
data <- data[-sample(nrow(data), round(0.15 * nrow(data))), ] # missed prompts
rownames(data) <- NULL
head(data)
#>   Participant                Time Happy Cheerful Content Sad Energetic Alert
#> 1         P01 2025-03-03 09:27:08    56       71      78  22        86    67
#> 2         P01 2025-03-03 11:53:59    59       70      73  26        58    73
#> 3         P01 2025-03-03 14:48:59    65       73      74  15        86    77
#> 4         P01 2025-03-03 17:43:07    56       72      69  38        62    62
#> 5         P01 2025-03-04 08:30:40    69       73      73  28        61    63
#> 6         P01 2025-03-04 15:27:25    82       96     100  13        56    72
#>   Active Tired
#> 1     47    26
#> 2     36    43
#> 3     59    15
#> 4     54    28
#> 5     43    44
#> 6     58    19

Each row is one answered notification (about 15% of the notifications were missed), with the participant, the time, and the 8 items.

Multilevel factor analysis

We ask for 2 factors and tell fa_multilevel() that observations are grouped by participant, using the familiar mixed-model syntax:

efa <- fa_multilevel(
    data,
    nfactors = 2,
    random = ~ (1 | Participant),
    items = items
)
#> Fitting the factor model with glmmTMB (may take a while)...
#> Done in 10.4 seconds.
efa
#> ===== Multilevel Exploratory Factor Analysis =====
#>   Items        : 8
#>   Observations : 1020
#>   Random       : ~(1 | Participant)
#>   Groups       : Participant = 30
#>   Factors      : 2 (rotation: oblimin)
#> 
#> Standardised within-level loadings:
#>              F1    F2   h2   u2
#> Happy      0.82 -0.01 0.67 0.33
#> Cheerful   0.82  0.03 0.69 0.31
#> Content    0.79 -0.02 0.62 0.38
#> Sad       -0.77  0.00 0.59 0.41
#> Energetic  0.01  0.74 0.55 0.45
#> Alert     -0.01  0.74 0.55 0.45
#> Active     0.03  0.66 0.45 0.55
#> Tired      0.02 -0.78 0.60 0.40
#> 
#>                  F1   F2
#> SS loadings    2.58 2.15
#> Proportion Var 0.32 0.27
#> 
#> Factor correlations:
#>      F1   F2
#> F1 1.00 0.22
#> F2 0.22 1.00
#> 
#> Variance decomposition (share of each item's total variance):
#>       Item Participant Factors Residual
#>      Happy        0.45    0.37     0.18
#>   Cheerful        0.43    0.39     0.18
#>    Content        0.43    0.35     0.22
#>        Sad        0.31    0.41     0.28
#>  Energetic        0.35    0.36     0.29
#>      Alert        0.43    0.31     0.26
#>     Active        0.33    0.30     0.37
#>      Tired        0.27    0.44     0.30
#> 
#> Fit: logLik = -8177.4, AIC = 16488.7, BIC = 16818.8 (df = 67)
#>   Factor scores : use `$scores`
#>   glmmTMB model : use `$model`
#> ==================================================

The output reads like a regular factor analysis:

  • Loadings: F1 is valence (Happy, Cheerful, Content, and negatively Sad) and F2 is arousal (Energetic, Alert, Active, and negatively Tired). These loadings describe how items co-fluctuate within a person, around that person’s own averages.
  • Factor correlations: valence and arousal correlate at 0.22 from moment to moment (the simulation used .30).
  • Variance decomposition: the share of each item’s variance that is due to stable differences between participants (Participant, similar to an intraclass correlation), to the factors, and to residual noise. Here, about 37% of the variance reflects stable differences between people.

Behind the scenes, each participant gets their own average on each item (random intercepts), and the factors are estimated on the deviations from these averages.

Tables and plots

The results work with the easystats ecosystem. model_parameters(), from the parameters package, returns the loadings in the same format as parameters::factor_analysis(). Here, we sort the items by factor and hide the loadings below .30, and display() formats them as a table for reports:

library(parameters)

loadings <- model_parameters(efa, sort = TRUE, threshold = 0.3)
display(loadings)
Rotated loadings from Factor Analysis (oblimin-rotation)
Variable F1 F2 Complexity Uniqueness
Happy 0.82 1.00 0.33
Cheerful 0.82 1.00 0.31
Content 0.79 1.00 0.38
Sad -0.77 1.00 0.41
Tired -0.78 1.00 0.40
Alert 0.74 1.00 0.45
Energetic 0.74 1.00 0.45
Active 0.66 1.00 0.55

The 2 latent factors (oblimin rotation) accounted for 59.07% of the total variance of the original data (F1 = 32.19%, F2 = 26.88%).

summary() gives the variance explained by each factor, and the correlation between the factors:

display(summary(loadings))
(Explained) Variance of Components
Parameter F1 F2
Eigenvalues 2.926 1.800
Variance Explained 0.322 0.269
Variance Explained (Cumulative) 0.322 0.591
Variance Explained (Proportion) 0.545 0.455
Factor Correlations
Factor F1 F2
F1 1.000 0.219
F2 0.219 1.000

As with the output of fa_multilevel(), these loadings and the variance explained describe the within-person level: the “total variance” is the moment-to-moment variance of the items, once the stable differences between participants have been removed.

The see package plots the loadings, either as bars:

plot(loadings)

or as a diagram (which needs the ggraph and tidygraph packages), where we can also name the factors:

plot(loadings, type = "graph", names_factors = c("Valence", "Arousal"))

Why not a regular factor analysis?

Without the random argument (it defaults to NULL), fa_multilevel() runs a standard factor analysis (the same model as stats::factanal() or psych::fa(fm = "ml")), ignoring that observations come from the same participants:

efa_regular <- fa_multilevel(data, nfactors = 2, items = items, verbose = FALSE)

data.frame(
    Regular = round(unclass(efa_regular$loadings), 2),
    Multilevel = round(unclass(efa$loadings), 2)
)
#>           Regular.F1 Regular.F2 Multilevel.F1 Multilevel.F2
#> Happy           0.89      -0.04          0.82         -0.01
#> Cheerful        0.83       0.06          0.82          0.03
#> Content         0.84       0.02          0.79         -0.02
#> Sad            -0.83       0.03         -0.77          0.00
#> Energetic       0.04       0.82          0.01          0.74
#> Alert          -0.01       0.79         -0.01          0.74
#> Active          0.06       0.66          0.03          0.66
#> Tired           0.05      -0.79          0.02         -0.78

The structure looks similar, but the regular analysis inflates the loadings and, above all, the correlation between valence and arousal: 0.53 instead of 0.22. This is because people who are generally happier also tend to be generally more energetic, and the regular analysis counts these stable differences as if they were moment-to-moment co-fluctuations.

How many factors?

Because the model has a proper likelihood, solutions with different numbers of factors can be compared with information criteria. Give nfactors a range of values to fit and compare them all:

efa_k <- fa_multilevel(
    data,
    nfactors = 1:3,
    random = ~ (1 | Participant),
    items = items,
    verbose = FALSE
)
efa_k
#> ===== Multilevel EFA: comparing numbers of factors =====
#>   Items        : 8
#>   Observations : 1020
#>   Random       : ~(1 | Participant)
#>   Rotation     : oblimin
#> 
#>  Factors  logLik     AIC     BIC Delta_BIC BIC_weight Explained        
#>        1 -8810.2 17740.4 18036.0    1217.2       0.00      0.34        
#>        2 -8177.4 16488.7 16818.8       0.0       1.00      0.59 <- best
#>        3 -8174.7 16495.3 16855.0      36.2       0.00      0.64        
#> 
#>   Explained: proportion of within-level item variance explained by the factors.
#>   Best solution (lowest BIC) : 2 factor(s), use `$best`
#>   All solutions              : `$solutions$n1`, `$solutions$n2`, `$solutions$n3`
#> ========================================================

The 2-factor solution has the lowest BIC (lower is better), which matches the simulation. BIC_weight expresses the relative support for each solution, and Explained shows that a third factor would add little. The best solution is available as efa_k$best, and all of them in efa_k$solutions (e.g., efa_k$solutions$n3 for the 3-factor solution).

Factor scores

$scores contains one row per observation, with the factor scores in place of the items, and all the other columns (participant, time) kept. Let’s give the factors their names:

scores <- efa$scores
names(scores)[match(c("F1", "F2"), names(scores))] <- c("Valence", "Arousal")
head(scores)
#>   Participant                Time     Valence    Arousal
#> 1         P01 2025-03-03 09:27:08 -0.38176734  0.4403415
#> 2         P01 2025-03-03 11:53:59 -0.54970299 -0.8182211
#> 3         P01 2025-03-03 14:48:59 -0.05782853  1.2723020
#> 4         P01 2025-03-03 17:43:07 -0.85100892 -0.2103002
#> 5         P01 2025-03-04 08:30:40 -0.28213128 -0.8814343
#> 6         P01 2025-03-04 15:27:25  1.39993360  0.3221333

These scores describe each participant’s momentary state relative to their own averages:

long <- tidyr::pivot_longer(
    scores[scores$Participant %in% c("P01", "P02", "P03"), ],
    cols = c("Valence", "Arousal"),
    names_to = "Dimension",
    values_to = "Score"
)

ggplot(long, aes(x = Time, y = Score, color = Dimension)) +
    geom_line() +
    geom_point(size = 1) +
    facet_wrap(~Participant, ncol = 1) +
    labs(x = NULL, y = "Factor score (within-person)") +
    theme_minimal()

Next steps: dynamics

The scores can go straight into the rest of the experdyn pipeline. Note that the factor analysis is run on the raw observations, before resampling: interpolated data points would artificially inflate the sample size.

resampled <- resample_timeseries(
    scores,
    time_col = "Time",
    participant_col = "Participant",
    plot = FALSE,
    verbose = FALSE
)
statespace <- make_statespace(resampled, delay = 1, dimensions = 2)
statespace
#> ========= Multivariate State Space =========
#>   Delay (rows)         : 1
#>   Dimensions           : 2
#>   Variables embedded   : 2
#>   Series processed     : 172
#>   Series embedded      : 172
#>   Embedded rows        : 2039
#>   Data frame           : use `$embedded` to extract
#> ============================================

From here, compute_rqa() and compute_mvsampen() characterise the dynamics of each participant in the valence-arousal space.

Good to know

  • Several grouping variables can be combined, crossed (e.g., random = ~ (1 | Participant) + (1 | Day) for events shared by everyone on a given day) or nested (random = ~ (1 | Site / Participant)). Each grouping variable needs enough levels: its item covariance matrix has to be estimated.
  • Missing answers are handled by using all available responses.
  • Items are treated as continuous. Short Likert scales (e.g., 1-5) are only approximately continuous.
  • Autocorrelation (carry-over from one prompt to the next) is not modelled. This does not bias the loadings, but observations are treated as exchangeable within each participant.
  • Rotation: the default is "oblimin" (correlated factors); other rotations are available through rotate (e.g., "varimax", "promax", "geominQ").