Latent class and latent trajectory analysis with the flexmix R package

Author

Kuan Liu

1. Hands-on example of a two-step latent class analysis

1.1 The PBC data (pbcseq in the survival R package)

  • Design: Mayo Clinic randomized trial of D-penicillamine versus placebo in primary biliary cirrhosis (PBC), 1974 to 1984.

  • pbcseq contains the 312 randomized patients with their baseline visit and follow-up visits (at 6 months, 1 year, and yearly thereafter). At each visit, clinical signs (ascites, hepatomegaly, spiders, edema) and liver laboratory values (bilirubin, albumin, prothrombin time, etc.) were recorded.

  • The outcome is time to death or transplant (futime, in days, and status: 0 = censored, 1 = transplant, 2 = death).

Variable Description Units / Levels
id Patient number -
futime Follow-up time days
status Endpoint status 0 = censored; 1 = transplant; 2 = dead
trt Treatment assignment 1 = D-penicillamine; 0 = placebo (note: coded 1/2 in the pbc data, 1/0 in pbcseq)
age Age at enrolment years
sex Sex m / f
day Time of the visit since enrolment days (0 = baseline)
ascites Presence of ascites at the visit 0 / 1
hepato Hepatomegaly at the visit 0 / 1
spiders Spider angiomas at the visit 0 / 1
edema Edema at the visit 0 = none; 0.5 = untreated or successfully treated; 1 = edema despite diuretics
bili Serum bilirubin mg/dL
chol Serum cholesterol mg/dL
albumin Serum albumin g/dL
alk.phos Alkaline phosphatase U/L
ast Aspartate aminotransferase U/L
platelet Platelet count -
protime Prothrombin time seconds
stage Histologic stage of disease at baseline 1 to 4
  • Note: with 312 patients we are below the sample size of 500 or more recommended by Sinha et al (2021) for latent class analysis; this is a teaching example.
library(survival)   # pbcseq data and survival analysis
library(flexmix)    # finite mixture models: latent class and latent trajectory analysis
library(tidyverse)  # data management and plots
library(gtsummary)  # summary and regression tables
library(survminer)  # Kaplan-Meier plots
library(DT)         # interactive tables
library(tidyLPA)    # calc_lrt() for the Lo-Mendell-Rubin (LMR) test

pbcseq <- survival::pbcseq   # copy the data from the survival package;

# look at the data: one row per patient per visit;
datatable(head(pbcseq, 20), rownames = FALSE, options = list(dom = "t"))
str(pbcseq)
'data.frame':   1945 obs. of  19 variables:
 $ id      : int  1 1 2 2 2 2 2 2 2 2 ...
 $ futime  : int  400 400 5169 5169 5169 5169 5169 5169 5169 5169 ...
 $ status  : int  2 2 0 0 0 0 0 0 0 0 ...
 $ trt     : int  1 1 1 1 1 1 1 1 1 1 ...
 $ age     : num  58.8 58.8 56.4 56.4 56.4 ...
 $ sex     : Factor w/ 2 levels "m","f": 2 2 2 2 2 2 2 2 2 2 ...
 $ day     : int  0 192 0 182 365 768 1790 2151 2515 2882 ...
 $ ascites : int  1 1 0 0 0 0 1 1 1 1 ...
 $ hepato  : int  1 1 1 1 1 1 1 1 1 1 ...
 $ spiders : int  1 1 1 1 1 1 1 1 1 1 ...
 $ edema   : num  1 1 0 0 0 0 0.5 1 1 1 ...
 $ bili    : num  14.5 21.3 1.1 0.8 1 1.9 2.6 3.6 4.2 3.6 ...
 $ chol    : int  261 NA 302 NA NA NA 230 NA NA 244 ...
 $ albumin : num  2.6 2.94 4.14 3.6 3.55 3.92 3.32 2.92 2.73 2.8 ...
 $ alk.phos: int  1718 1612 7395 2107 1711 1365 1110 996 860 779 ...
 $ ast     : num  138 6.2 113.5 139.5 144.2 ...
 $ platelet: int  190 183 221 188 161 122 135 100 103 113 ...
 $ protime : num  12.2 11.2 10.6 11 11.6 10.6 11.3 11.5 11.5 11.5 ...
 $ stage   : int  4 4 3 3 3 3 3 3 3 3 ...

1.2 Data set-up: one row per patient at baseline

  • For the baseline latent class analysis we keep one row per patient: the first visit (day = 0).

  • Cluster-defining variables (indicators), chosen because they describe the clinical severity of liver disease:

    • four binary clinical signs: ascites, hepatomegaly, spiders, any edema (edema 0.5 or 1 recoded as 1)
    • three continuous laboratory values: log(bilirubin), albumin, prothrombin time. Bilirubin is very right-skewed, so we use the log scale.
  • Variables not used for clustering (age, sex, treatment, stage, other labs) are kept for step 2, where we check whether the classes differ on them.

base <- pbcseq %>%
  group_by(id) %>%
  slice_min(day, n = 1, with_ties = FALSE) %>%   # first visit of each patient = baseline;
  ungroup() %>%
  mutate(
    # cluster-defining variables;
    edema_any = as.numeric(edema > 0),           # 1 = any edema (0.5 or 1), 0 = none;
    log_bili  = log(bili),                       # log scale to reduce skewness;
    # outcome and other baseline variables for step 2;
    death     = as.numeric(status == 2),         # 1 = died; 0 = alive or transplanted (censored);
    years     = futime / 365.25,                 # follow-up time in years;
    trt       = factor(trt, levels = c(0, 1), labels = c("Placebo", "D-penicillamine")),   # placebo = reference;
    stage     = factor(stage)
  ) %>%
  # keep patients with complete data on the 7 cluster-defining variables;
  drop_na(ascites, hepato, spiders, edema_any, log_bili, albumin, protime)

nrow(base)   # number of patients in the analysis;
[1] 312
# descriptive summary of the cluster-defining variables;
base %>%
  select(ascites, hepato, spiders, edema_any, bili, log_bili, albumin, protime) %>%
  tbl_summary(
    statistic = list(all_continuous() ~ "{mean} ({sd})",
                     all_categorical() ~ "{n} ({p}%)"),
    digits = list(all_continuous() ~ 2)
  ) %>%
  add_n()
Characteristic N N = 3121
ascites 312 24 (7.7%)
hepato 312 160 (51%)
spiders 312 90 (29%)
edema_any 312 65 (21%)
bili 312 3.22 (4.49)
log_bili 312 0.57 (1.03)
albumin 312 3.52 (0.42)
protime 312 10.71 (0.94)
1 n (%); Mean (SD)

1.3 Step 1: fit latent class models with 1 to 5 classes

How flexmix works:

  • flexmix() fits a finite mixture model: the population is assumed to be a mixture of K classes; within a class, each indicator follows its own distribution (Bernoulli for a 0/1 indicator, Normal for a continuous indicator) and the indicators are independent of each other (local independence).

  • The model driver tells flexmix what kind of indicators we have. FLXMCmvcombi() handles a mix of binary (0/1) and continuous columns. (For continuous indicators only, use FLXMCmvnorm(diagonal = TRUE); for binary indicators only, FLXMCmvbinary().)

  • The formula Y ~ 1 means the indicators in the matrix Y depend on the latent class only (no covariates).

  • stepFlexmix() fits the model for each candidate number of classes (k = 1:5). Because the EM algorithm can get stuck in a local maximum, it repeats each fit from nrep = 10 random starting values and keeps the best (highest log-likelihood) solution.

  • By default flexmix drops a class whose share of patients falls below 5% during estimation (minprior = 0.05), so a model requested with K classes may come back with fewer. The printed output shows k (classes kept) and k0 (classes requested).

# matrix of the 7 cluster-defining variables (rows = patients, columns = indicators);
Y <- as.matrix(base[, c("ascites", "hepato", "spiders", "edema_any",
                        "log_bili", "albumin", "protime")])

set.seed(2026)
lca_fits <- stepFlexmix(Y ~ 1,                     # indicators depend on the class only;
                        k = 1:5,                   # candidate number of classes;
                        nrep = 10,                 # random starts per K, best solution kept;
                        model = FLXMCmvcombi(),    # 0/1 columns -> Bernoulli, other columns -> Normal;
                        verbose = FALSE)

lca_fits   # k = classes kept, k0 = classes requested, logLik, AIC, BIC, ICL for each model;

Call:
stepFlexmix(Y ~ 1, model = FLXMCmvcombi(), k = 1:5, nrep = 10, 
    verbose = FALSE)

  iter converged k k0    logLik      AIC      BIC      ICL
1    2      TRUE 1  1 -1691.197 3402.394 3439.824 3439.824
2   12      TRUE 2  2 -1508.737 3059.475 3138.078 3195.263
3   31      TRUE 3  3 -1460.421 2984.842 3104.618 3186.998
4   89      TRUE 4  4 -1443.474 2972.948 3133.897 3247.573
5   77      TRUE 5  5 -1432.075 2972.150 3174.272 3299.502

1.4 Choose the number of classes

We compare the candidate models on the criteria from the lecture:

  1. Fit: BIC, lower is better.
  2. Test: the Lo-Mendell-Rubin (LMR) likelihood ratio test of K versus K-1 classes (a small p-value says K classes fit better than K-1).
  3. Classification certainty: relative entropy (0 to 1, above 0.8 is good) and the average posterior probability of the assigned class (above 0.7 is good).
  4. Class size: avoid very small classes.

The posterior probabilities come from posterior() (one row per patient, one column per class) and the assigned class from clusters() (the class with the highest posterior probability).

# BIC of each fitted model (lower is better);
BIC(lca_fits)
       1        2        3        4        5 
3439.824 3138.078 3104.618 3133.897 3174.272 
# table to collect the fit statistics, one row per candidate K;
fit_table <- data.frame(K = 2:5, BIC = NA, entropy = NA, avg_posterior = NA, smallest_class = NA)

# loop over the candidate models K = 2, 3, 4, 5 (model K is stored at position K because we fitted k = 1:5);
for (K in 2:5) {

  fit_K   <- getModel(lca_fits, which = K)   # the fitted model with K classes;
  post_K  <- posterior(fit_K)                # posterior probabilities: patients x classes;
  class_K <- clusters(fit_K)                 # assigned (modal) class of each patient;

  # relative entropy: 1 - (sum of -p*log(p)) / (N * log(K)); pmax() avoids log(0);
  entropy_K <- 1 - sum(-post_K * log(pmax(post_K, 1e-12))) / (nrow(post_K) * log(ncol(post_K)))

  # average posterior probability of the class each patient was assigned to;
  avg_post_K <- mean(post_K[cbind(1:nrow(post_K), class_K)])

  # save the results of this K in row K - 1 of the table;
  fit_table$BIC[K - 1]            <- BIC(fit_K)
  fit_table$entropy[K - 1]        <- entropy_K
  fit_table$avg_posterior[K - 1]  <- avg_post_K
  fit_table$smallest_class[K - 1] <- min(table(class_K))
}

fit_table
  K      BIC   entropy avg_posterior smallest_class
1 2 3138.078 0.7463280     0.9235329            111
2 3 3104.618 0.7508073     0.8883338             42
3 4 3133.897 0.7276958     0.8492599             44
4 5 3174.272 0.7344814     0.8341502             22
# average posterior probability by class for one model (example: K = 3);
fit_3   <- getModel(lca_fits, which = 3)
post_3  <- posterior(fit_3)
class_3 <- clusters(fit_3)
tapply(post_3[cbind(1:nrow(post_3), class_3)], class_3, mean)
        1         2         3 
0.9124378 0.8916492 0.8784026 

The LMR test compares each model with the model with one class fewer. calc_lrt() needs the sample size, the log-likelihood, the number of estimated parameters and the number of classes of the two models being compared.

# log-likelihood and number of parameters of each model;
fit_1 <- getModel(lca_fits, which = 1)
fit_2 <- getModel(lca_fits, which = 2)
fit_4 <- getModel(lca_fits, which = 4)
fit_5 <- getModel(lca_fits, which = 5)

# 1 class (null) vs 2 classes (alternative);
calc_lrt(n = nrow(base),
         null_ll = as.numeric(logLik(fit_1)), null_param = attr(logLik(fit_1), "df"), null_classes = 1,
         alt_ll  = as.numeric(logLik(fit_2)), alt_param  = attr(logLik(fit_2), "df"), alt_classes  = 2)
Lo-Mendell-Rubin ad-hoc adjusted likelihood ratio rest:

LR = 364.919, LMR LR (df = 11) = 344.901, p < 0.001
# 2 classes (null) vs 3 classes (alternative);
calc_lrt(n = nrow(base),
         null_ll = as.numeric(logLik(fit_2)), null_param = attr(logLik(fit_2), "df"), null_classes = 2,
         alt_ll  = as.numeric(logLik(fit_3)), alt_param  = attr(logLik(fit_3), "df"), alt_classes  = 3)
Lo-Mendell-Rubin ad-hoc adjusted likelihood ratio rest:

LR = 96.633, LMR LR (df = 11) = 91.332, p < 0.001
# 3 classes (null) vs 4 classes (alternative);
calc_lrt(n = nrow(base),
         null_ll = as.numeric(logLik(fit_3)), null_param = attr(logLik(fit_3), "df"), null_classes = 3,
         alt_ll  = as.numeric(logLik(fit_4)), alt_param  = attr(logLik(fit_4), "df"), alt_classes  = 4)
Lo-Mendell-Rubin ad-hoc adjusted likelihood ratio rest:

LR = 33.894, LMR LR (df = 11) = 32.035, p < 0.001
# 4 classes (null) vs 5 classes (alternative);
calc_lrt(n = nrow(base),
         null_ll = as.numeric(logLik(fit_4)), null_param = attr(logLik(fit_4), "df"), null_classes = 4,
         alt_ll  = as.numeric(logLik(fit_5)), alt_param  = attr(logLik(fit_5), "df"), alt_classes  = 5)
Lo-Mendell-Rubin ad-hoc adjusted likelihood ratio rest:

LR = 22.798, LMR LR (df = 11) = 21.548, p = 0.028
  • No single criterion decides. In practice we look for the K where the BIC stops improving, the LMR test is no longer significant, entropy and average posterior probability are good, and all classes are large enough to be useful as subgroups.

  • In this example the BIC is lowest for 3 classes, the average posterior probability of the assigned class is close to 0.9, and the smallest class has about 40 patients. We therefore continue with 3 classes (K_final below); change this number if you want to explore another solution.

1.5 Describe the final classes

K_final   <- 3
lca_final <- getModel(lca_fits, which = K_final)

summary(lca_final)   # prior = class proportion, size = number of patients assigned, ratio = classification quality;

Call:
stepFlexmix(Y ~ 1, model = FLXMCmvcombi(), k = 3, nrep = 10, 
    verbose = FALSE)

       prior size post>0 ratio
Comp.1 0.138   42    218 0.193
Comp.2 0.428  126    305 0.413
Comp.3 0.434  144    236 0.610

'log Lik.' -1460.421 (df=32)
AIC: 2984.842   BIC: 3104.618 
# attach the assigned class to the baseline data;
base$class <- factor(paste0("Class", clusters(lca_final)))

table(base$class)

Class1 Class2 Class3 
    42    126    144 
# class profiles: the cluster-defining variables summarized by class;
base %>%
  select(class, ascites, hepato, spiders, edema_any, bili, albumin, protime) %>%
  tbl_summary(
    by = class,
    statistic = list(all_continuous() ~ "{median} ({p25}, {p75})",
                     all_categorical() ~ "{n} ({p}%)"),
    digits = list(all_continuous() ~ 1)
  ) %>%
  add_n() %>%
  bold_labels()
Characteristic N Class1
N = 421
Class2
N = 1261
Class3
N = 1441
ascites 312 22 (52%) 2 (1.6%) 0 (0%)
hepato 312 34 (81%) 91 (72%) 35 (24%)
spiders 312 28 (67%) 57 (45%) 5 (3.5%)
edema_any 312 33 (79%) 13 (10%) 19 (13%)
bili 312 6.6 (2.4, 16.2) 3.1 (1.9, 4.7) 0.8 (0.6, 1.1)
albumin 312 3.0 (2.6, 3.3) 3.5 (3.2, 3.7) 3.7 (3.5, 3.9)
protime 312 12.1 (11.4, 12.7) 10.6 (10.0, 11.3) 10.2 (9.9, 10.7)
1 n (%); Median (Q1, Q3)

A profile plot of the standardized indicator means by class (as in Figure 1 of Sinha et al) makes it easy to name the classes: an indicator with mean z-score above 0 is higher than average in that class, below 0 is lower than average.

profile_df <- base %>%
  select(class, ascites, hepato, spiders, edema_any, log_bili, albumin, protime) %>%
  mutate(across(-class, ~ as.numeric(scale(.x)))) %>%   # standardize each indicator: mean 0, SD 1;
  pivot_longer(-class, names_to = "indicator", values_to = "z") %>%
  group_by(class, indicator) %>%
  summarise(mean_z = mean(z), .groups = "drop") %>%
  mutate(indicator = factor(indicator, levels = c("ascites", "hepato", "spiders", "edema_any",
                                                  "log_bili", "albumin", "protime")))

ggplot(profile_df, aes(x = indicator, y = mean_z, group = class, colour = class)) +
  geom_hline(yintercept = 0, linetype = "dashed", colour = "grey50") +
  geom_line(linewidth = 1) +
  geom_point(size = 2) +
  scale_colour_brewer(palette = "Dark2") +
  labs(x = NULL, y = "Mean standardized value (z-score)", colour = "Class",
       title = paste0("Latent class profiles at baseline (K = ", K_final, ")")) +
  theme_minimal()

1.6 Step 2: classes versus baseline characteristics not used in clustering

In step 2 the class label is treated as an observed categorical variable. First we check whether the classes differ on baseline variables that were not used to build them (age, sex, treatment arm, histologic stage, other labs). This is a check that the classes capture something clinically meaningful; the p-values come from chi-square or Kruskal-Wallis tests.

base %>%
  select(class, age, sex, trt, stage, chol, alk.phos, ast, platelet) %>%
  tbl_summary(
    by = class,
    statistic = list(all_continuous() ~ "{median} ({p25}, {p75})",
                     all_categorical() ~ "{n} ({p}%)"),
    digits = list(all_continuous() ~ 1),
    missing = "ifany"
  ) %>%
  add_n() %>%
  bold_labels()
Characteristic N Class1
N = 421
Class2
N = 1261
Class3
N = 1441
age 312 55.1 (49.0, 61.2) 47.3 (40.9, 56.4) 49.7 (42.1, 56.4)
sex 312


    m
4 (9.5%) 22 (17%) 10 (6.9%)
    f
38 (90%) 104 (83%) 134 (93%)
trt 312


    Placebo
19 (45%) 66 (52%) 69 (48%)
    D-penicillamine
23 (55%) 60 (48%) 75 (52%)
stage 312


    1
0 (0%) 2 (1.6%) 14 (9.7%)
    2
1 (2.4%) 20 (16%) 46 (32%)
    3
8 (19%) 49 (39%) 63 (44%)
    4
33 (79%) 55 (44%) 21 (15%)
chol 284 255.0 (203.0, 394.5) 352.0 (264.5, 453.0) 290.5 (247.0, 356.5)
    Unknown
6 6 16
alk.phos 312 1,574.5 (933.0, 3,292.0) 1,554.5 (1,052.0, 2,276.0) 1,073.0 (723.0, 1,640.5)
ast 312 147.3 (101.9, 182.9) 129.5 (102.3, 167.4) 91.5 (71.3, 127.1)
platelet 308 174.5 (122.0, 227.0) 248.0 (188.0, 318.0) 280.5 (232.0, 336.5)
    Unknown
0 0 4
1 Median (Q1, Q3); n (%)

1.7 Step 2: classes versus survival

km_fit <- survfit(Surv(years, death) ~ class, data = base)

ggsurvplot(
  km_fit,
  data         = base,
  conf.int     = TRUE,
  pval         = TRUE,          # log-rank test p-value;
  risk.table   = TRUE,
  xlab         = "Years since enrolment",
  ylab         = "Survival probability",
  legend.title = "Class",
  ggtheme      = theme_minimal()
)

# Cox model: hazard of death by class, adjusted for age and sex;
coxph(Surv(years, death) ~ class + age + sex, data = base) %>%
  tbl_regression(exponentiate = TRUE)
Characteristic HR 95% CI p-value
class


    Class1 — —
    Class2 0.31 0.21, 0.48 <0.001
    Class3 0.07 0.04, 0.12 <0.001
age 1.03 1.01, 1.05 <0.001
sex


    m — —
    f 0.82 0.52, 1.28 0.4
Abbreviations: CI = Confidence Interval, HR = Hazard Ratio

1.8 Step 2: the class as a subgroup variable for HTE

Finally, the class can be used as the subgroup variable in a treatment-outcome model with an interaction term, exactly as in a conventional subgroup analysis. Here the treatment is D-penicillamine versus placebo.

# model without and with the treatment x class interaction;
cox_main <- coxph(Surv(years, death) ~ trt + class + age + sex, data = base)
cox_int  <- coxph(Surv(years, death) ~ trt * class + age + sex, data = base)

# likelihood ratio test for the interaction: is the treatment effect different between classes?
anova(cox_main, cox_int)
Analysis of Deviance Table
 Cox model: response is  Surv(years, death)
 Model 1: ~ trt + class + age + sex
 Model 2: ~ trt * class + age + sex
   loglik Chisq Df Pr(>|Chi|)
1 -653.26                    
2 -651.22 4.084  2     0.1298
# treatment effect within each class: writing class + class:trt (instead of trt*class) makes R
# estimate one treatment hazard ratio per class directly;
coxph(Surv(years, death) ~ class + class:trt + age + sex, data = base) %>%
  tbl_regression(exponentiate = TRUE)
Characteristic HR 95% CI p-value
class


    Class1 — —
    Class2 0.19 0.10, 0.34 <0.001
    Class3 0.05 0.02, 0.10 <0.001
age 1.03 1.01, 1.05 <0.001
sex


    m — —
    f 0.81 0.52, 1.27 0.4
class * trt


    Class1 * D-penicillamine 0.46 0.25, 0.88 0.018
    Class2 * D-penicillamine 1.05 0.66, 1.69 0.8
    Class3 * D-penicillamine 0.84 0.41, 1.71 0.6
Abbreviations: CI = Confidence Interval, HR = Hazard Ratio

2. Hands-on example of latent trajectory classes

We now use the repeated measurements of bilirubin to identify classes of patients with different bilirubin trajectories over the first 3 years, using group-based trajectory modelling (GBTM) with flexmix. The two-step approach is then the same as above.

2.1 Data set-up: one row per patient per visit

  • We keep the visits in the first 3 years and patients with at least two visits in that window (one measurement does not define a trajectory).

  • The repeated outcome is log(bilirubin); year is the time of the visit in years since enrolment.

long <- pbcseq %>%
  mutate(year     = day / 365.25,        # visit time in years;
         log_bili = log(bili)) %>%
  filter(year <= 3) %>%                  # visits in the first 3 years;
  select(id, year, log_bili) %>%
  drop_na() %>%
  group_by(id) %>%
  filter(n() >= 2) %>%                   # at least two visits per patient;
  ungroup() %>%
  arrange(id, year)

length(unique(long$id))   # number of patients;
[1] 285
nrow(long)                # number of visits;
[1] 1099
# spaghetti plot: one line per patient;
ggplot(long, aes(x = year, y = log_bili, group = id)) +
  geom_line(alpha = 0.15) +
  geom_point(alpha = 0.15, size = 0.6) +
  labs(x = "Years since enrolment", y = "log(bilirubin)",
       title = "Individual bilirubin trajectories, first 3 years") +
  theme_minimal()

2.2 Step 1: fit trajectory models with 1 to 5 classes

  • Each class has its own mean trajectory, a quadratic curve in time: log_bili ~ poly(year, 2, raw = TRUE).

  • | id tells flexmix that all visits of the same patient belong to the same class, so the patient (not the visit) is classified.

  • The default model driver FLXMRglm() fits a Normal regression within each class, which is what we need for a continuous outcome.

set.seed(2026)
traj_fits <- stepFlexmix(log_bili ~ poly(year, 2, raw = TRUE) | id,   # quadratic trajectory per class, grouped by patient;
                         data = long,
                         k = 1:5,
                         nrep = 10,
                         verbose = FALSE)

traj_fits

Call:
stepFlexmix(log_bili ~ poly(year, 2, raw = TRUE) | id, data = long, 
    k = 1:5, nrep = 10, verbose = FALSE)

  iter converged k k0     logLik      AIC      BIC      ICL
1    2      TRUE 1  1 -1638.8358 3285.672 3305.680 3305.680
2   25      TRUE 2  2 -1200.8302 2419.660 2464.680 2480.544
3   16      TRUE 3  3 -1034.9970 2097.994 2168.024 2194.504
4   38      TRUE 4  4  -969.3873 1976.775 2071.815 2111.402
5   58      TRUE 5  5  -922.7350 1893.470 2013.522 2059.102

2.3 Choose the number of trajectory classes

Same criteria as before. One difference: posterior() and clusters() return one row per visit; all rows of a patient are identical, so we keep the first row of each patient to compute the statistics per patient.

first_row <- !duplicated(long$id)   # TRUE for the first visit of each patient;

traj_table <- data.frame(K = 2:5, BIC = NA, entropy = NA, avg_posterior = NA, smallest_class = NA)

for (K in 2:5) {

  fit_K   <- getModel(traj_fits, which = K)
  post_K  <- posterior(fit_K)[first_row, ]     # one row per patient;
  class_K <- clusters(fit_K)[first_row]        # one class per patient;

  entropy_K  <- 1 - sum(-post_K * log(pmax(post_K, 1e-12))) / (nrow(post_K) * log(ncol(post_K)))
  avg_post_K <- mean(post_K[cbind(1:nrow(post_K), class_K)])

  traj_table$BIC[K - 1]            <- BIC(fit_K)
  traj_table$entropy[K - 1]        <- entropy_K
  traj_table$avg_posterior[K - 1]  <- avg_post_K
  traj_table$smallest_class[K - 1] <- min(table(class_K))
}

traj_table
  K      BIC   entropy avg_posterior smallest_class
1 2 2464.680 0.9109684     0.9758296            131
2 3 2168.024 0.9118772     0.9605197             82
3 4 2071.815 0.8930845     0.9411528             61
4 5 2013.522 0.8936783     0.9319253             26
# LMR test, K vs K-1, using the number of patients as n;
n_pat <- length(unique(long$id))
tfit_1 <- getModel(traj_fits, which = 1)
tfit_2 <- getModel(traj_fits, which = 2)
tfit_3 <- getModel(traj_fits, which = 3)
tfit_4 <- getModel(traj_fits, which = 4)

# 1 vs 2 classes;
calc_lrt(n = n_pat,
         null_ll = as.numeric(logLik(tfit_1)), null_param = attr(logLik(tfit_1), "df"), null_classes = 1,
         alt_ll  = as.numeric(logLik(tfit_2)), alt_param  = attr(logLik(tfit_2), "df"), alt_classes  = 2)
Lo-Mendell-Rubin ad-hoc adjusted likelihood ratio rest:

LR = 876.011, LMR LR (df = 5) = 827.228, p < 0.001
# 2 vs 3 classes;
calc_lrt(n = n_pat,
         null_ll = as.numeric(logLik(tfit_2)), null_param = attr(logLik(tfit_2), "df"), null_classes = 2,
         alt_ll  = as.numeric(logLik(tfit_3)), alt_param  = attr(logLik(tfit_3), "df"), alt_classes  = 3)
Lo-Mendell-Rubin ad-hoc adjusted likelihood ratio rest:

LR = 331.666, LMR LR (df = 5) = 313.197, p < 0.001
# 3 vs 4 classes;
calc_lrt(n = n_pat,
         null_ll = as.numeric(logLik(tfit_3)), null_param = attr(logLik(tfit_3), "df"), null_classes = 3,
         alt_ll  = as.numeric(logLik(tfit_4)), alt_param  = attr(logLik(tfit_4), "df"), alt_classes  = 4)
Lo-Mendell-Rubin ad-hoc adjusted likelihood ratio rest:

LR = 131.220, LMR LR (df = 5) = 123.912, p < 0.001
  • For trajectory models with many repeated measurements, the BIC often keeps decreasing as classes are added, as it does here. Entropy stays high for all K, so the decision rests on class size and interpretability: we continue with 3 classes (low and stable, intermediate, high and rising bilirubin), which are easy to describe and large enough to be used as subgroups. A 4-class solution would also be defensible.

2.4 Describe the final trajectory classes

K_traj     <- 3   # change to the K you chose from the results above;
traj_final <- getModel(traj_fits, which = K_traj)

summary(traj_final)

Call:
stepFlexmix(log_bili ~ poly(year, 2, raw = TRUE) | id, data = long, 
    k = 3, nrep = 10, verbose = FALSE)

       prior size post>0 ratio
Comp.1 0.353  398    709 0.561
Comp.2 0.352  395    562 0.703
Comp.3 0.295  306    497 0.616

'log Lik.' -1034.997 (df=14)
AIC: 2097.994   BIC: 2168.024 
# class-specific trajectory coefficients (intercept, year, year^2) and residual SD;
parameters(traj_final)
                                     Comp.1      Comp.2      Comp.3
coef.(Intercept)                 0.39567780 -0.42676004 1.680680414
coef.poly(year, 2, raw = TRUE)1 -0.03564158 -0.06854729 0.243398506
coef.poly(year, 2, raw = TRUE)2  0.08280662  0.03342825 0.007135072
sigma                            0.47703969  0.36478405 0.680213927
# one class per patient;
traj_class <- data.frame(id         = long$id[first_row],
                         traj_class = factor(paste0("Traj", clusters(traj_final)[first_row])))

table(traj_class$traj_class)

Traj1 Traj2 Traj3 
  102   101    82 
# add the class to the long data for plotting;
long <- long %>% left_join(traj_class, by = "id")

# spaghetti plot by class with the class mean curves (quadratic fit within each class);
ggplot(long, aes(x = year, y = log_bili)) +
  geom_line(aes(group = id), alpha = 0.1) +
  geom_smooth(aes(colour = traj_class), method = "lm", formula = y ~ poly(x, 2),
              se = FALSE, linewidth = 1.2) +
  scale_colour_brewer(palette = "Dark2") +
  labs(x = "Years since enrolment", y = "log(bilirubin)", colour = "Trajectory class",
       title = paste0("Latent bilirubin trajectory classes (K = ", K_traj, ")")) +
  theme_minimal()

2.5 Step 2: trajectory classes versus baseline characteristics

Baseline characteristics were measured before the trajectory, so they can be compared across the trajectory classes directly. We also cross-tabulate the baseline latent classes (Section 1) with the trajectory classes.

# merge the trajectory class into the baseline data (patients with a trajectory only);
base_traj <- base %>% inner_join(traj_class, by = "id")

base_traj %>%
  select(traj_class, age, sex, trt, stage, bili, albumin, protime, ascites, hepato, spiders, edema_any) %>%
  tbl_summary(
    by = traj_class,
    statistic = list(all_continuous() ~ "{median} ({p25}, {p75})",
                     all_categorical() ~ "{n} ({p}%)"),
    digits = list(all_continuous() ~ 1),
    missing = "ifany"
  ) %>%
  add_n() %>%
  bold_labels()
Characteristic N Traj1
N = 1021
Traj2
N = 1011
Traj3
N = 821
age 285 48.7 (39.2, 56.0) 50.4 (43.0, 56.4) 48.9 (42.5, 58.6)
sex 285


    m
13 (13%) 5 (5.0%) 14 (17%)
    f
89 (87%) 96 (95%) 68 (83%)
trt 285


    Placebo
50 (49%) 52 (51%) 42 (51%)
    D-penicillamine
52 (51%) 49 (49%) 40 (49%)
stage 285


    1
2 (2.0%) 12 (12%) 1 (1.2%)
    2
18 (18%) 34 (34%) 12 (15%)
    3
46 (45%) 42 (42%) 27 (33%)
    4
36 (35%) 13 (13%) 42 (51%)
bili 285 1.4 (1.1, 2.1) 0.7 (0.5, 0.8) 5.2 (3.4, 7.3)
albumin 285 3.5 (3.4, 3.7) 3.7 (3.5, 4.0) 3.3 (3.1, 3.7)
protime 285 10.3 (9.9, 11.0) 10.4 (10.0, 10.8) 11.0 (10.0, 11.5)
ascites 285 5 (4.9%) 1 (1.0%) 8 (9.8%)
hepato 285 56 (55%) 27 (27%) 60 (73%)
spiders 285 34 (33%) 9 (8.9%) 33 (40%)
edema_any 285 18 (18%) 14 (14%) 20 (24%)
1 Median (Q1, Q3); n (%)

2.6 Step 2: trajectory classes versus survival after a landmark

  • The trajectory classes are built from measurements taken during the first 3 years of follow-up. A patient has to survive to show a 3-year trajectory, so comparing survival from enrolment would be biased (immortal time bias).

  • Landmark approach: we restrict the survival analysis to patients still alive and not transplanted at 3 years, and we count survival time from year 3 onward.

landmark <- base_traj %>%
  filter(years > 3) %>%                 # alive and not transplanted at the 3-year landmark;
  mutate(years_lm = years - 3)          # survival time measured from year 3;

nrow(landmark)   # patients in the landmark analysis;
[1] 233
km_traj <- survfit(Surv(years_lm, death) ~ traj_class, data = landmark)

ggsurvplot(
  km_traj,
  data         = landmark,
  conf.int     = TRUE,
  pval         = TRUE,
  risk.table   = TRUE,
  xlab         = "Years since the 3-year landmark",
  ylab         = "Survival probability",
  legend.title = "Trajectory class",
  ggtheme      = theme_minimal()
)

# Cox model from the landmark, adjusted for age and sex;
coxph(Surv(years_lm, death) ~ traj_class + age + sex, data = landmark) %>%
  tbl_regression(exponentiate = TRUE)
Characteristic HR 95% CI p-value
traj_class


    Traj1 — —
    Traj2 0.30 0.17, 0.54 <0.001
    Traj3 4.90 2.79, 8.61 <0.001
age 1.04 1.02, 1.06 <0.001
sex


    m — —
    f 0.96 0.52, 1.77 0.9
Abbreviations: CI = Confidence Interval, HR = Hazard Ratio