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)
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 analysislibrary(flexmix) # finite mixture models: latent class and latent trajectory analysislibrary(tidyverse) # data management and plotslibrary(gtsummary) # summary and regression tableslibrary(survminer) # Kaplan-Meier plotslibrary(DT) # interactive tableslibrary(tidyLPA) # calc_lrt() for the Lo-Mendell-Rubin (LMR) testpbcseq <- 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.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;
We compare the candidate models on the criteria from the lecture:
Fit: BIC, lower is better.
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).
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).
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)
# 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 in2: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
# 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
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 <-3lca_final <-getModel(lca_fits, which = K_final)summary(lca_final) # prior = class proportion, size = number of patients assigned, ratio = classification quality;
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.
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
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 in2: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
# 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
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)
# 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