Skip to main content

22  Semiparametric Ordinal Longitudinal Models

MOST: Markov Ordinal State Transition model

Key references

22.1 Longitudinal Ordinal Models as Unifying Concepts

This material in this section is taken from hbiostat.org/talks/rcteff.html. See also hbiostat.org/proj/covid19/ordmarkov.html and hbiostat.org/endpoint and Ordinal state transition models as a unifying risk prediction framework.

22.1.1 General Outcome Attributes

  • Timing and severity of outcomes
  • Handle
    • terminal events (death)
    • non-terminal events (MI, stroke)
    • recurrent events (hospitalization)
  • Break the ties; the more levels of Y the better: fharrell.com/post/ordinal-info
    • Maximum power when there is only one patient at each level (continuous Y)

22.1.2 What is a Fundamental Outcome Assessment?

  • In a given week or day what is the severity of the worst thing that happened to the patient?
  • Expert clinician consensus of outcome ranks
  • Spacing of outcome categories irrelevant
  • Avoids defining additive weights for multiple events on same week
  • Events can be graded & can code common co-occurring events as worse event
  • Can translate an ordinal longitudinal model to obtain a variety of estimates
    • time until a condition
    • expected time in state
  • Bayesian partial proportional odds model can compute the probability that the treatment affects mortality differently than it affects nonfatal outcomes
  • Model also elegantly handles partial information: at each day/week the ordinal Y can be left, right, or interval censored when a range of the scale was not measured

22.1.3 Examples of Longitudinal Ordinal Outcomes

  • 0=alive 1=dead
    • censored at 3w: 000
    • death at 2w: 01
    • longitudinal binary logistic model OR \(\approx\) HR
  • 0=at home 1=hospitalized 2=MI 3=dead
    • hospitalized at 3w, rehosp at 7w, MI at 8w & stays in hosp, f/u ends at 10w: 0010001211
  • 0-6 QOL excellent–poor, 7=MI 8=stroke 9=dead
    • QOL varies, not assessed in 3w but pt event free, stroke at 8w, death 9w: 12[0-6]334589
    • MI status unknown at 7w: 12[0-6]334[5-7]891
    • Can make first 200 levels be a continuous response variable and the remaining values represent clinical event overrides

1 Better: treat the outcome as being in one of two non-contiguous values {5,7} instead of [5-7] but no software is currently available for this

22.1.4 Statistical Model

  • Proportional odds ordinal logistic model with covariate adjustment
  • Patient random effects (intercepts) handle intra-patient correlation
  • Better fitting: Markov model
    • handles absorbing states, extremely high day-to-day correlations within subject
    • faster, flexible, uses standard software
    • state transition probabilities
    • after fit translate to unconditional state occupancy probabilities
    • use these to estimate expected time in a set of states (e.g., on ventilator or dead); restricted mean survival time without assuming PH
  • Extension of binary logistic model
  • Generalization of Wilcoxon-Mann-Whitney Two-Sample Test
  • No assumption about Y distribution for a given patient type
  • Does not use the numeric Y codes

22.1.5 Model Robustness

  • If \(Y\) consists of different event types, model will not fit well unless non-PO is allowed for time
  • Model has a high chance of finding the best treatment even if PO is assumed for treatment and it is strongly violated
  • Probabiliity estimates for being in specific states may be inaccurate for some levels of \(X\) if PO is falsely assumed for \(X\)
  • State occupancy probabilities and expected time in states are relatively robust
  • Uncertainties in \(\hat{\beta}\) may be very inaccurate if correlation structure is badly misspecified
    • Frequentist: SEs too small and \(\alpha\) inflated; Bayesian: posteriors too narrow, posterior probs miscalibrated
  • Example: ORBITA (Personal communication, Matthew Shun-Shin, Imperial College, London)
    • Daily angina frequency with huge within-person variability
    • May lead a Markov model to think that prior states are irrelevant
    • \(\rightarrow\) multiple observations on a subject have the same information as new subjects
    • \(\rightarrow\) inflates apparent effective sample size
    • Need to incorporate each subject’s latent angina tendencies to account for this
    • Most easily done with random intercepts
  • Include random intercepts to protect against deflation of uncertainties in \(\beta\)
    • Serial correlation dominant structure \(\rightarrow\) variance of random effects small and including them unnecessarily will not harm the analysis
    • Compound symmetry dominant structure \(\rightarrow\) inclusion of lags in the model will not harm the analysis, and effects of lags may be small
    • Bayesian modeling handles random effects much more naturally
      • Automatic marginalization over random effects when examining posterior draws for \(\beta\)

22.2 Case Studies

  • Random effects model for continuous Y: Section 7.8.4
  • Markov model for continuous Y: Section 7.8.5
  • Multiple detailed case studies for discrete ordinal Y: hbiostat.org/proj/covid19.
    • ORCHID: hydroxychloroquine for treatment of COVID-19 with patient assessment on select days
    • VIOLET: vitamin D for serious respiratory illness with assessment on 28 consecutive days
      • Large power gain demonstrated over time to recovery or ordinal status at a given day
      • Loosely speaking serial assessments for each 5 day period had the same statistical information as a new patient assessed once
    • ACTT-1: NIH-NIAID Remdesivir study for treatment of COVID-19 with daily assessment while in hospital, select days after that with interval censoring
      • Assesses time-varying effect of remdesivir
      • Handles death explicitly, unlike per-patient time to recovery
    • Other: Bayesian and frequentist power simulation, exploration of unequal time gaps, etc.

22.3 Case Study For 4-Level Ordinal Longitudinal Outcome

  • VIOLET: randomized clinical trial of seriously ill adults in ICUs to study the effectiveness of vitamin D vs. placebo
  • Daily ordinal outcomes assessed for 28 days with very little missing data
  • Original paper: DOI:10.1056/NEJMoa1911124 focused on 1078 patients with confirmed baseline vitamin D deficiency
  • Focus on 1352 of the original 1360 randomized patients
  • Extensive re-analyses:
  • Fitted a frequentist first-order Markov partial proportional odds (PO) model to 1352 VIOLET patients using the R VGAM package to simulate 250,000 patient longitudinal records with daily assessments up to 28d: hbiostat.org/data/repo/simlongord.html
  • Simulation inserted an odds ratio of 0.75 for tx=1 : tx=0 (log OR = -0.288)
  • Case study uses the first 500 simulated patients
    • 13203 records
    • average of 26.4 records per patient out of a maximum of 28, due to deaths
    • full 250,000 and 500-patient datasets available at hbiostat.org/data
  • 4-level outcomes:
    • patient at home
    • in hospital or other health facility
    • on ventilator or diagnosed with acute respiratory distress syndrome (ARDS)
    • dead
  • Death is an absorbing state
    • only possible previous states are the first 3
    • at baseline no one was at home
    • a patient who dies has Dead as the status on their final record, with no “deaths carried forward”
    • later we will carry deaths forward just to be able to look at empirical state occupancy probabilities (SOPs) vs. model estimates
  • Frequentist modeling using the VGAM package allows us to use the unconstrained partial PO (PPO) model with regard to time, but does not allow us to compute uncertainty intervals for derived parameters (e.g., SOPs and mean time in states)
  • Can use the bootstrap to obtain approximate confidence limits (as below)
  • Bayesian analysis using the rmsb package provides exact uncertainty intervals for derived parameters but at present rmsb only implements the constrained PPO model when getting predicted values
  • PPO for time allows mix of outcomes to change over time (which occurred in the real data)
  • Model specification:
    • For day \(t\) let \(Y(t)\) denote the ordinal outcome for a patient
      \(\Pr(Y \geq y | X, Y(t-1)) = \text{expit}(\alpha_{y} + X\beta + g(Y(t-1), t))\)

    • \(g\) contains regression coefficients for the previous state \(Y(t-1)\) effect, the absolute time \(t\) effect, and any \(y\)-dependency on the \(t\) effect (non-PO for \(t\))

    • Baseline covariates: age, SOFA score (a measure of organ function), treatment (tx)

    • Time-dependent covariate: previous state (yprev, 3 levels)

    • Time trend: linear spline with knot at day 2 (handles exception at day 1 when almost no one was sent home)

    • Changing mix of outcomes over time

      • effect of time on transition ORs for different cutoffs of Y
      • 2 time components (one slope change) \(\times\) 3 Y cutoffs = 6 parameters related to day
  • Reverse coding of Y so that higher levels are worse

22.3.1 Descriptives

  • all state transitions from one day to the next
  • SOPs estimated by proportions (need to carry death forward)
Code
getHdata(simlongord500)
d <- simlongord500
setDT(d, key='id')
d[, y     := factor(y,     levels=rev(levels(y    )))]
d[, yprev := factor(yprev, levels=rev(levels(yprev)))]
setnames(d, 'time', 'day')
# Show descriptive statistics for baseline data
describe(d[day == 1, .(yprev, age, sofa, tx)], 'Baseline Variables')
Baseline Variables Descriptives
Baseline Variables

4 Variables   500 Observations

yprev
nmissingdistinct
50002
 Value      In Hospital/Facility            Vent/ARDS
 Frequency                   340                  160
 Proportion                 0.68                 0.32 

age
image
nmissingdistinctInfoMeanpMedianGmd.05.10.25.50.75.90.95
5000730.99956.0856.517.4928.9536.0046.0058.0067.0075.1079.05
lowest : 19 20 21 22 23 , highest: 89 90 91 92 94
sofa
image
nmissingdistinctInfoMeanpMedianGmd.05.10.25.50.75.90.95
5000180.9925.27453.901 0.00 1.00 3.00 5.00 7.2510.0011.00
 Value          0     1     2     3     4     5     6     7     8     9    10    11
 Frequency     38    38    41    51    59    53    58    37    24    32    32    17
 Proportion 0.076 0.076 0.082 0.102 0.118 0.106 0.116 0.074 0.048 0.064 0.064 0.034
                                               
 Value         12    13    14    15    17    18
 Frequency      8     4     4     2     1     1
 Proportion 0.016 0.008 0.008 0.004 0.002 0.002 

tx
nmissingdistinctInfoSumMean
500020.752560.512

Code
# Check that death can only occur on the last day
d[, .(ddif=if(any(y == 'Dead')) min(day[y == 'Dead']) -
                                max(day) else NA_integer_),
          by=id][, table(ddif)]
ddif
 0 
51 
Code
dd <- datadist(d); options(datadist='dd')
Code
require(ggplot2)
propsTrans(y ~ day + id, data=d, maxsize=4, arrow='->') +
    theme(axis.text.x=element_text(angle=90, hjust=1))
Figure 22.1: Transition proportions from data simulated from VIOLET

Show state occupancy proportions by creating a data table with death carried forward.

Code
w <- d[day < 28 & y == 'Dead', ]
w[, if(.N > 1) stop('Error: more than one death record'), by=id]
Empty data.table (0 rows and 1 cols): id
Code
w <- w[, .(day = (day + 1) : 28, y = y, tx=tx), by=id]
u <- rbind(d, w, fill=TRUE)
setkey(u, id)
u[, Tx := paste0('tx=', tx)]
propsPO(y ~ day + Tx, data=u) +
  guides(fill=guide_legend(title='Status')) +
  theme(legend.position='bottom', axis.text.x=element_text(angle=90, hjust=1))
Figure 22.2: State occupancy proportions from simulated VIOLET data with death carried forward

22.3.2 Model Fitting

  • Fit the PPO first-order Markov model without assuming PO for the time effect
  • Elapsed time frequently has a non-PO effect when Y contains different event types, due to some types of events tending to occur earlier than some other types
  • Also fit a model that has linear splines with more knots to add flexibility in how time and baseline covariates are transformed
  • ytrans=‘all’ for orm and borm mean to fit the unconstrained (with regard to Y) partial PO model
  • For our 4-level outcome, there are two non-proportional odds parameters (\(\tau\)s) per y-dependent effect column
  • Since we are only allowing time to be in non-PO, when time is modeled linearly there are 2 \(\tau\)s
  • When day is modeled as linear spline with one knot (one slope change) there are 4 \(\tau\)s
Code
# Use the vglm code if you want to use the VGAM package
# f <- vglm(ordered(y) ~ yprev + lsp(day, 2) + age + sofa + tx,
#           cumulative(reverse=TRUE, parallel=FALSE ~ lsp(day, 2)), data=d)
# summary(f)
# g <- vglm(ordered(y) ~ yprev + lsp(day, c(2, 4, 8, 15)) +
#             lsp(age, c(35, 60, 75)) + lsp(sofa, c(2, 6, 10)) + tx,
#           cumulative(reverse=TRUE, parallel=FALSE ~ lsp(day, c(2, 4, 8, 15))),
#           data=d)
# summary(g)
f <- orm(y ~ yprev + lsp(day, 2) + age + sofa + tx,
         ~ lsp(day, 2), ytrans='all', x=TRUE, y=TRUE, data=d)
f

Logistic (Proportional Odds) Ordinal Regression Model

orm(formula = y ~ yprev + lsp(day, 2) + age + sofa + tx, yde = ~lsp(day, 
    2), ytrans = "all", data = d, x = TRUE, y = TRUE)

Frequencies of Responses

                Home In Hospital/Facility            Vent/ARDS 
                8141                 3887                  913 
                Dead 
                  51 
Model Likelihood
Ratio Test
Discrimination
Indexes
Rank Discrim.
Indexes
Obs12992 LR χ217896.14 R20.910 ρ0.827
ESS9443 d.f.11 R211,129920.748 Dxy0.965
Distinct Y4 P(>χ2)<0.0001 R211,94430.850
Y0.51 Score χ216958.92 |P(Y ≥ Y0.5)-½|0.468
max |∂log L/∂β|2×10-11 P(>χ2)<0.0001
β S.E. Wald Z P(>|Z|)
y≥In Hospital/Facility   -5.0297  0.6284 -8.00 <0.0001
y≥Vent/ARDS  -13.1928  0.5777 -22.84 <0.0001
y≥Dead  -19.5798  0.9364 -20.91 <0.0001
yprev=In Hospital/Facility   8.7731  0.2657 33.01 <0.0001
yprev=Vent/ARDS   15.1383  0.3220 47.01 <0.0001
day   -1.4315  0.2841 -5.04 <0.0001
day'   1.4844  0.2858 5.19 <0.0001
age   0.0113  0.0028 4.05 <0.0001
sofa   0.0641  0.0126 5.09 <0.0001
tx   -0.1114  0.0846 -1.32 0.1879
day × Vent/ARDS   0.7241  0.3806 1.90 0.0571
day' × Vent/ARDS   -0.7384  0.3847 -1.92 0.0549
day × Dead   1.5689  0.5477 2.86 0.0042
day' × Dead   -1.6041  0.5547 -2.89 0.0038
Code
g <- orm(y ~ yprev + lsp(day, c(2, 4, 8, 15)) +
         lsp(age, c(35, 60,75)) + lsp(sofa, c(2, 6, 10)) + tx,
         ~ lsp(day, c(2, 4, 8, 15)), ytrans='all', data=d)
g

Logistic (Proportional Odds) Ordinal Regression Model

orm(formula = y ~ yprev + lsp(day, c(2, 4, 8, 15)) + lsp(age, 
    c(35, 60, 75)) + lsp(sofa, c(2, 6, 10)) + tx, yde = ~lsp(day, 
    c(2, 4, 8, 15)), ytrans = "all", data = d)

Frequencies of Responses

                Home In Hospital/Facility            Vent/ARDS 
                8141                 3887                  913 
                Dead 
                  51 
Model Likelihood
Ratio Test
Discrimination
Indexes
Rank Discrim.
Indexes
Obs12992 LR χ217907.88 R20.910 ρ0.827
ESS9443 d.f.26 R226,129920.748 Dxy0.965
Distinct Y4 P(>χ2)<0.0001 R226,94430.849
Y0.51 Score χ216992.89 |P(Y ≥ Y0.5)-½|0.468
max |∂log L/∂β|4×10-11 P(>χ2)<0.0001
β S.E. Wald Z P(>|Z|)
y≥In Hospital/Facility   -4.5407  0.8861 -5.12 <0.0001
y≥Vent/ARDS  -12.8715  0.8563 -15.03 <0.0001
y≥Dead  -18.8522  1.1798 -15.98 <0.0001
yprev=In Hospital/Facility   8.7688  0.2685 32.65 <0.0001
yprev=Vent/ARDS   15.1196  0.3251 46.50 <0.0001
day   -1.5537  0.3051 -5.09 <0.0001
day'   1.7226  0.3535 4.87 <0.0001
day''   -0.1425  0.1406 -1.01 0.3109
day'''   0.0249  0.0763 0.33 0.7437
day''''   0.0018  0.0520 0.03 0.9727
age   -0.0038  0.0192 -0.20 0.8412
age'   0.0192  0.0235 0.82 0.4141
age''   -0.0154  0.0161 -0.96 0.3379
age'''   0.0360  0.0269 1.33 0.1820
sofa   0.1709  0.0959 1.78 0.0749
sofa'   -0.1369  0.1225 -1.12 0.2638
sofa''   0.0183  0.0692 0.26 0.7914
sofa'''   0.0741  0.0892 0.83 0.4057
tx   -0.1229  0.0853 -1.44 0.1497
day × Vent/ARDS   0.9082  0.4258 2.13 0.0329
day' × Vent/ARDS   -1.0469  0.5276 -1.98 0.0472
day'' × Vent/ARDS   0.1306  0.2487 0.53 0.5996
day''' × Vent/ARDS   -0.0459  0.1423 -0.32 0.7469
day'''' × Vent/ARDS   0.0909  0.0952 0.95 0.3398
day × Dead   1.3354  0.6744 1.98 0.0477
day' × Dead   -1.1348  0.8854 -1.28 0.1999
day'' × Dead   -0.2917  0.4105 -0.71 0.4773
day''' × Dead   -0.0539  0.2402 -0.22 0.8223
day'''' × Dead   0.2092  0.1760 1.19 0.2345
Code
lrtest(g, f)

Model 1: y ~ yprev + lsp(day, c(2, 4, 8, 15)) + lsp(age, c(35, 60, 75)) + 
    lsp(sofa, c(2, 6, 10)) + tx
Model 2: y ~ yprev + lsp(day, 2) + age + sofa + tx

L.R. Chisq       d.f.          P 
11.7332705 15.0000000  0.6990959 
Code
AIC(f); AIC(g)
[1] 4537.04
[1] 4555.307

We will use the simpler model, which has the better (smaller) AIC. Check the PO assumption on time by comparing the simpler model’s AIC to the AIC from a fully PO model.

Code
# h <- vglm(ordered(y) ~ yprev + lsp(day, 2) + age + sofa + tx,
#           cumulative(reverse=TRUE, parallel=TRUE), data=d)
h <- orm(y ~ yprev + lsp(day, 2) + age + sofa + tx, data=d)
lrtest(f, h)

Model 1: y ~ yprev + lsp(day, 2) + age + sofa + tx
Model 2: y ~ yprev + lsp(day, 2) + age + sofa + tx

 L.R. Chisq        d.f.           P 
10.66970367  4.00000000  0.03053794 
Code
AIC(f); AIC(h)
[1] 4537.04
[1] 4539.71

The model allowing for non-PO in time is better. Now show likelihood ratio tests on the parameters.

Code
anova(f, test='LR')

Likelihood Ratio Statistics for y

χ2 d.f. P
yprev 14159.51 2 <0.0001
day 77.21 6 <0.0001
 Nonlinear 47.24 3 <0.0001
age 16.36 1 <0.0001
sofa 26.29 1 <0.0001
tx 1.74 1 0.1877
TOTAL 17896.14 11 <0.0001
Code
# Use this to get Wald tests if using VGAM::vglm
wald <- function(f) {
  se <- sqrt(diag(vcov(f)))
  s <- round(cbind(beta=coef(f), SE=se, Z=coef(f) / se), 3)
  a <- c('>= in hospital/facility', '>= vent/ARDS', 'dead',
         'previous state in hospital/facility',
         'previous state vent/ARDS',
         'initial slope for day, >= hospital/facility',
         'initial slope for day, >= vent/ARDS',
         'initial slope for day, dead',
         'slope increment, >= hospital/facilty',
         'slope increment, >= vent/ARDS',
         'slope increament, dead',
         'baseline age linear effect',
         'baseline SOFA score linear effect',
         'treatment log OR')
  rownames(s) <- a
  s
}
wald(f)

We see evidence for a benefit of treatment. Compute the treatment transition OR and approximate 0.95 confidence interval. Also compute 3 transition ORs for the time effect. There are 3 because day was allowed to have a y-dependent effect. For all the other predictors there is only one odds ratio for a given range of predictor values.

Code
summary(f, ycut='In Hospital/Facility')
Low High Δ Effect S.E. Lower 0.95 Upper 0.95
day 7 21 14 7.416e-01 0.11750 5.113e-01 9.718e-01
 Odds Ratio 7 21 14 2.099e+00 1.668e+00 2.643e+00
age 45 66 21 2.374e-01 0.05862 1.225e-01 3.523e-01
 Odds Ratio 45 66 21 1.268e+00 1.130e+00 1.422e+00
sofa 3 7 4 2.563e-01 0.05035 1.576e-01 3.550e-01
 Odds Ratio 3 7 4 1.292e+00 1.171e+00 1.426e+00
tx 0 1 1 -1.114e-01 0.08461 -2.772e-01 5.442e-02
 Odds Ratio 0 1 1 8.946e-01 7.579e-01 1.056e+00
yprev --- In Hospital/Facility:Home 1 2 8.773e+00 0.26570 8.252e+00 9.294e+00
 Odds Ratio 1 2 6.458e+03 3.836e+03 1.087e+04
yprev --- Vent/ARDS:Home 1 3 1.514e+01 0.32200 1.451e+01 1.577e+01
 Odds Ratio 1 3 3.754e+06 1.997e+06 7.056e+06
Code
summary(f, ycut='Vent/ARDS')
Low High Δ Effect S.E. Lower 0.95 Upper 0.95
day 7 21 14 5.408e-01 0.16830 2.110e-01 8.707e-01
 Odds Ratio 7 21 14 1.717e+00 1.235e+00 2.388e+00
age 45 66 21 2.374e-01 0.05862 1.225e-01 3.523e-01
 Odds Ratio 45 66 21 1.268e+00 1.130e+00 1.422e+00
sofa 3 7 4 2.563e-01 0.05035 1.576e-01 3.550e-01
 Odds Ratio 3 7 4 1.292e+00 1.171e+00 1.426e+00
tx 0 1 1 -1.114e-01 0.08461 -2.772e-01 5.442e-02
 Odds Ratio 0 1 1 8.946e-01 7.579e-01 1.056e+00
yprev --- In Hospital/Facility:Home 1 2 8.773e+00 0.26570 8.252e+00 9.294e+00
 Odds Ratio 1 2 6.458e+03 3.836e+03 1.087e+04
yprev --- Vent/ARDS:Home 1 3 1.514e+01 0.32200 1.451e+01 1.577e+01
 Odds Ratio 1 3 3.754e+06 1.997e+06 7.056e+06
Code
summary(f, ycut='Dead')
Low High Δ Effect S.E. Lower 0.95 Upper 0.95
day 7 21 14 2.485e-01 0.29300 -3.257e-01 8.227e-01
 Odds Ratio 7 21 14 1.282e+00 7.220e-01 2.277e+00
age 45 66 21 2.374e-01 0.05862 1.225e-01 3.523e-01
 Odds Ratio 45 66 21 1.268e+00 1.130e+00 1.422e+00
sofa 3 7 4 2.563e-01 0.05035 1.576e-01 3.550e-01
 Odds Ratio 3 7 4 1.292e+00 1.171e+00 1.426e+00
tx 0 1 1 -1.114e-01 0.08461 -2.772e-01 5.442e-02
 Odds Ratio 0 1 1 8.946e-01 7.579e-01 1.056e+00
yprev --- In Hospital/Facility:Home 1 2 8.773e+00 0.26570 8.252e+00 9.294e+00
 Odds Ratio 1 2 6.458e+03 3.836e+03 1.087e+04
yprev --- Vent/ARDS:Home 1 3 1.514e+01 0.32200 1.451e+01 1.577e+01
 Odds Ratio 1 3 3.754e+06 1.997e+06 7.056e+06
Code
# lor <- coef(f)['tx']
# se  <- sqrt(vcov(f)['tx', 'tx'])
# b   <- exp(lor + qnorm(0.975) * se * c(0, -1, 1))
# names(b) <- c('OR', 'Lower', 'Upper')
# round(b, 3)

The maximum likelihood estimate of the OR is somewhat at odds with the true OR of 0.75 on which the simulations were based.

22.3.3 Covariate Effects

  • Most interesting covariate effect is effect of time since randomization
Code
w     <- d[day == 1]
ycuts <- levels(d$y)[-1]

dat <- expand.grid(yprev = 'In Hospital/Facility', age=median(w$age),
                   sofa=median(w$sofa), tx=0, day=1:28)
z <- expand.grid(mod=c('model with few knots','model with more knots'),
                 y=ycuts)
setDT(z)
h <- function(mod) {
  m  <- if(mod == 'model with few knots') f else g
  xb <- qlogis(predict(m, dat, type='fitted'))
  data.table(day=as.vector(row(xb)),
             y=as.vector(colnames(xb)[col(xb)]),
             xbeta=as.vector(xb))
}
u <- z[, h(mod), by=.(mod)]
ggplot(u, aes(x=day, y=xbeta, color=y)) + geom_line() +
  facet_wrap(~ mod, ncol=2) +
  xlab('Day') + ylab('Log Odds') +
  labs(caption='Relative log odds of transitioning from in hospital/facility to indicated status')
Figure 22.3: Estimated time trends in relative log odds of transitions. Variables not shown are set to median/mode and tx=0.

22.3.4 Correlation Structure

  • The data were simulated under a first-order Markov process so it doesn’t make sense to check correlation pattern assumptions for our model
  • When the simulated data were created, the within-patient correlation pattern was checked against the pattern from the fitted model by simulating a large trial from the model fit and comparing correlations in the simulated data to those in the real data
  • It showed excellent agreement
  • Let’s compute the Spearman \(\rho\) correlation matrix on the 500 patient dataset and show the matrix from the real data next to it
  • Delete day 28 from the new correlation matrix to conform with correlation matrix computed on real data
  • Also show correlation matrix from 10,000 patient sample
  • Heights of bars are proportional to Spearman \(\rho\)
Code
# Tall and thin -> short and wide data table
w <- dcast(d[, .(id, day, y=as.numeric(y))],
           id ~ day, value.var='y')
r <- cor(as.matrix(w[, -1]), use='pairwise.complete.obs',
         method='spearman')[-28, -28]
p <- plotCorrM(r, xangle=90)
p[[1]] + theme(legend.position='none') +
  labs(caption='Spearman correlation matrix from 500 patient dataset')

Code
vcorr <- readRDS('markov-vcorr.rds')
ra    <- vcorr$r.actual
plotCorrM(ra, xangle=90)[[1]] + theme(legend.position='none') +
  labs(caption='Spearman correlation matrix from actual data')

Code
rc    <- vcorr$r.simulated
plotCorrM(rc, xangle=90)[[1]] + theme(legend.position='none') +
  labs(caption='Spearman correlation matrix from 10,000 simulated patients')

  • Estimating the whole correlation matrix from 500 patients is noisy
  • Compute the mean absolute difference between two correlation matrices (the first on 10,000 simulated patients assuming a first-order Markov process and the second from the real data)
  • Compute means of mean absolute differences stratified by the day involved
Code
ad <- abs(rc[-28, -28] - ra)
round(apply(ad, 1, mean), 2)
   1    2    3    4    5    6    7    8    9   10   11   12   13   14   15   16 
0.09 0.05 0.05 0.05 0.04 0.03 0.03 0.02 0.02 0.02 0.02 0.02 0.02 0.03 0.02 0.02 
  17   18   19   20   21   22   23   24   25   26   27 
0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 

Actual and simulated with-patient correlations agree well except when day 1 is involved.

Code
p[[2]]
Figure 22.4: Variogram-like graph for checking intra-patient correlation structure. \(x\)-axis shows the number of days between two measurements.
  • Usual serial correlation declining pattern; outcome status values become less correlated within patient as time gap increases
  • Also see non-isotropic pattern: correlations depend also on absolute time, not just gap

Formal Goodness of Fit Assessments for Correlation Structure

  • Data simulation model \(\rightarrow\) we already know that the first order Markov process has to fit
  • Do two formal assessments to demonstrate how this can be done in general. Both make the correlation structure more versatile.
    • Add patient-specific intercepts to see if a compound symmetry structure adds anything to the first-order Markov structure
    • Add a dependency on state before last in addition to our model’s dependency on the last state to see if a second-order Markov process fits better

Add Random Effects

  • Bayesian models handle random effects more naturally than frequentist models \(\rightarrow\) use a Bayesian partial PO first-order Markov model (R rmsb package)
  • Use cmdstan software in place of the default of rstan
Code
cmdstanr::set_cmdstan_path(cmdstan.loc)   # cmdstan.loc is defined in ~/.Rprofile
options(prType='html')
# Use 4 cores since 4 chains
options(mc.cores = 4, rmsb.backend='cmdstan')
seed <- 2   # The following took 15m using 4 cores
# Specify adapt_delta since the default of 0.8 resulted in divergent samples
b <- borm(y ~ yprev + lsp(day, 2) + age + sofa + tx + cluster(id),
          ~ lsp(day, 2), ytrans='all', data=d,
          sampling.args=list(adapt_delta = 0.95),
          file='markov-bppo.rds')
Running MCMC with 4 parallel chains...
Chain 4 finished in 515.9 seconds.
Chain 2 finished in 628.1 seconds.
Chain 3 finished in 631.3 seconds.
Chain 1 finished in 637.6 seconds.

All 4 chains finished successfully.
Mean chain execution time: 603.2 seconds.
Total execution time: 637.7 seconds.
Code
stanDx(b)
Iterations: 2000 on each of 4 chains, with 4000 posterior distribution samples saved

For each parameter, n_eff is a crude measure of effective sample size
and Rhat is the potential scale reduction factor on split chains
(at convergence, Rhat=1)


Checking sampler transitions for divergences.
1 of 4000 (0.03%) transitions ended with a divergence.
These divergent transitions indicate that HMC is not fully able to explore the posterior distribution.
Try increasing adapt delta closer to 1.
If this doesn't remove all divergences, try to reparameterize the model.

Checking E-BFMI - sampler transitions HMC potential energy.
E-BFMI satisfactory.

Rank-normalized split effective sample size satisfactory for all parameters.

The following parameters had rank-normalized split R-hat greater than 1.01:
  sigmag[1]
Such high values indicate incomplete mixing and biased estimation.
You should consider regularizing your model with additional prior information or a more effective parameterization.

Processing complete.
Divergent samples: 1 0 0 0 

EBFMI: 0.456 0.443 0.396 0.406 

   Parameter  Rhat ESS bulk ESS tail
1   alpha[1] 1.001     2547     2724
2   alpha[2] 1.001     1512     2651
3   alpha[3] 1.003     1134     2265
4    beta[1] 1.000     2349     2714
5    beta[2] 1.000     2396     2206
6    beta[3] 1.004      648     1051
7    beta[4] 1.000     3666     2814
8    beta[5] 1.001     2440     2149
9    beta[6] 1.004      872     1354
10   beta[7] 1.002     4339     3013
11  tau[1,1] 1.002     4722     3189
12  tau[2,1] 1.001     3775     3115
13  tau[1,2] 1.001     4507     2988
14  tau[2,2] 1.001     4054     3079
15 sigmag[1] 1.016      258      732
Code
b

Bayesian Logistic (Proportional Odds) Ordinal Regression Model

Dirichlet Priors With Concentration Parameter 0.455 for Intercepts

borm(formula = y ~ yprev + lsp(day, 2) + age + sofa + tx + cluster(id), 
    yde = ~lsp(day, 2), ytrans = "all", data = d, file = "markov-bppo.rds", 
    sampling.args = list(adapt_delta = 0.95))

Frequencies of Responses

                Home In Hospital/Facility            Vent/ARDS 
                8141                 3887                  913 
                Dead 
                  51 
Mixed Calibration/
Discrimination Indexes
Discrimination
Indexes
Rank Discrim.
Indexes
Obs12992 B0.028 [0.028, 0.029] |P(Y ≥ Y0.5)-½|0.467 [0.465, 0.471] ρ0.83 [0.83, 0.83]
Distinct Y4 C0.983 [0.983, 0.983]
p7 Dxy0.966 [0.966, 0.967]
Draws4000
Chains4
Time679.6s
Cluster onid
Clusters500
σγ0.3712 [0.0171, 0.6354]
Mean β Median β S.E. Lower Upper P(β>0) Symmetry
y≥In Hospital/Facility   -4.8132   -4.8123  0.6493   -6.0057   -3.5273  0.0000  1.10
y≥Vent/ARDS  -13.1435  -13.1390  0.5904  -14.3000  -12.0319  0.0000  0.95
y≥Dead  -19.8432  -19.8205  0.9774  -21.6748  -17.9047  0.0000  0.88
yprev=In Hospital/Facility   8.6407   8.6335  0.2806   8.0751   9.1774  1.0000  1.07
yprev=Vent/ARDS   15.0485   15.0493  0.3326   14.4080   15.6935  1.0000  1.07
day   -1.5043   -1.4972  0.2936   -2.0847   -0.9434  0.0000  0.92
day'   1.5478   1.5396  0.2947   0.9789   2.1281  1.0000  1.09
age   0.0124   0.0124  0.0032   0.0063   0.0188  1.0000  1.01
sofa   0.0753   0.0745  0.0161   0.0446   0.1069  1.0000  1.15
tx   -0.1144   -0.1138  0.0932   -0.2997   0.0622  0.1098  0.97
day × Vent/ARDS   0.7516   0.7484  0.3865   -0.0454   1.4670  0.9755  1.05
day' × Vent/ARDS   -0.7661   -0.7631  0.3898   -1.5014   0.0269  0.0230  0.95
day × Dead   1.6884   1.6757  0.5632   0.6706   2.8284  0.9998  1.12
day' × Dead   -1.7234   -1.7095  0.5697   -2.8723   -0.6945  0.0003  0.90
  • Note that borm parameterizes the partial PO parameters differently than VGAM::vglm.
  • Posterior median of the standard deviation of the random effects \(\sigma_\gamma\) is 0.40
  • This is fairly small on the logit scale in which most of the action takes place in \([-4, 4]\)
  • Random intercepts add an inconsequential improvement in the fit, justifying the Markov process’ conditional (on prior state) independence assumption
  • Another useful analysis would entail comparing the SD of the posterior distributions for the main parameters with and without inclusion of the random effects

Second-order Markov Process

  • On follow-up days 2-28
  • Frequentist partial PO model
Code
# Derive time-before-last states (lag-1 `yprev`)
h <- d[, yprev2 := shift(yprev), by=id]
h <- h[day > 1, ]
# Fit first-order model ignoring day 1 so can compare to second-order
# We have to make time linear since no day 1 data
# The VGAM package vglm function could have been used (slower)
# f1 <- vglm(ordered(y) ~ yprev + day + age + sofa + tx,
#            cumulative(reverse=TRUE, parallel=FALSE ~ day), data=h)
# f2 <- vglm(ordered(y) ~ yprev + yprev2 + day + age + sofa + tx,
#            cumulative(reverse=TRUE, parallel=FALSE ~ day), data=h)
f1 <- orm(y ~ yprev + day + age + sofa + tx, ~ day,
          ytrans='all', data=h)
f2 <- orm(y ~ yprev + yprev2 + day + age + sofa + tx, ~ day,
          ytrans='all', data=h)
lrtest(f2, f1)

Model 1: y ~ yprev + yprev2 + day + age + sofa + tx
Model 2: y ~ yprev + day + age + sofa + tx

L.R. Chisq       d.f.          P 
 1.1236104  2.0000000  0.5701788 
Code
AIC(f1); AIC(f2)
[1] 4212.051
[1] 4214.928
  • First-order model has better fit “for the money” by AIC
  • Formal chunk test of second-order terms not impressive

22.3.5 Computing Derived Quantities

From the fitted Markov state transition model, compute for one covariate setting and two treatments:

  • state occupancy probabilities
  • mean time in state
  • differences between treatments in mean time in state

To specify covariate setting:

  • most common initial state is In Hospital/Facility so use that
  • within that category look at relationship between the two covariates
  • they have no correlation so use the individual medians
Code
istate <- 'In Hospital/Facility'
w <- d[day == 1 & yprev == istate, ]
w[, cor(age, sofa, method='spearman')]
[1] 0.01651803
Code
x <- w[, lapply(.SD, median), .SDcols=Cs(age, sofa)]
adjto <- x[, paste0('age=', x[, age], '  sofa=', x[, sofa],
                    '  initial state=', istate)]
# Expand to cover both treatments and initial state
x <- cbind(tx=0:1, yprev=istate, x)
x
      tx                yprev   age  sofa
   <int>               <char> <num> <num>
1:     0 In Hospital/Facility    56     5
2:     1 In Hospital/Facility    56     5

Compute all SOPs for each treatment. soprobMarkovOrdm is in Hmisc.

Code
S <- z <- NULL
for(Tx in 0:1) {
  s <- soprobMarkovOrdm(f, x[tx == Tx, ], times=1:28, ylevels=levels(d$y),
                        absorb='Dead', tvarname='day')
  S <- rbind(S, cbind(tx=Tx, s))
  u <- data.frame(day=as.vector(row(s)), y=as.vector(col(s)), p=as.vector(s))
  u$tx <- Tx
  z <- rbind(z, u)
}
z$y <- factor(z$y, 1:4, levels(d$y))
revo <- function(z) {
  z <- as.factor(z)
  factor(z, levels=rev(levels(as.factor(z))))
}
ggplot(z, aes(x=factor(day), y=p, fill=revo(y))) +
    facet_wrap(~ paste('Treatment', tx), nrow=1) + geom_col() +
    xlab('Day') + ylab('Probability') +
    guides(fill=guide_legend(title='Status')) +
    labs(caption=paste0('Estimated state occupancy probabilities for\n',
                        adjto)) +
    theme(legend.position='bottom',
          axis.text.x=element_text(angle=90, hjust=1))
Figure 22.5: State occupancy probabilities for each treatment

Compute by treatment the mean time unwell (expected number of days not at home). Expected days in state is simply the sum over days of daily probabilities of being in that state.

Code
mtu  <- tapply(1. - S[, 'Home'], S[, 'tx'], sum)
dmtu <- diff(mtu)
w    <- c(mtu, dmtu)
names(w) <- c('tx=0', 'tx=1', 'Days Difference')
w
           tx=0            tx=1 Days Difference 
      9.5270484       8.5866986      -0.9403498 

We estimate that patients on treatment 1 have 1 less day unwell than those on treatment 0 for the given covariate settings.

Do a similar calculation for the expected number of days alive out of 28 days (similar to restricted mean survival time.

Code
mta <- tapply(1. - S[, 'Dead'], S[, 'tx'], sum)
w <- c(mta, diff(mta))
names(w) <- c('tx=0', 'tx=1', 'Days Difference')
w
           tx=0            tx=1 Days Difference 
    27.65094449     27.74380920      0.09286471 

22.3.6 Bootstrap Confidence Interval for Difference in Mean Time Unwell

  • Need to sample with replacement from patients, not records
    • code taken from rms package’s bootcov function
    • sampling patients entails including some patients multiple times and omitting others
    • save all the record numbers, group them by patient ID, sample from these IDs, then use all the original records whose record numbers correspond to the sampled IDs
  • Use the basic bootstrap to get 0.95 confidence intervals
  • Speed up the model fit by having each bootstrap fit use as starting parameter estimates the values from the original data fit
Code
B         <- 500    # number of bootstrap resamples
recno     <- split(1 : nrow(d), d$id)
npt       <- length(recno)   # 500
startbeta <- coef(f)
seed      <- 3
if(file.exists('markov-boot.rds')) {
  z        <- readRDS('markov-boot.rds')
  betas    <- z$betas
  diffmean <- z$diffmean
} else {
  betas <- diffmean <- numeric(B)
  ylev  <- levels(d$y)
  for(i in 1 : B) {
    j <- unlist(recno[sample(npt, npt, replace=TRUE)])
    # g <- vglm(ordered(y) ~ yprev + lsp(day, 2) + age + sofa + tx,
    #           cumulative(reverse=TRUE, parallel=FALSE ~ lsp(day, 2)),
    #           coefstart=startbeta, data=d[j, ])
    g <- orm(y ~ yprev + lsp(day, 2) + age + sofa + tx, ~ lsp(day, 2), ytrans='all', data=d[j, ])
    betas[i] <- coef(g)['tx']
    s0 <- soprobMarkovOrdm(g, x[tx == 0, ], times=1:28, ylevels=ylev,
                           absorb='Dead', tvarname='day')
    s1 <- soprobMarkovOrdm(g, x[tx == 1, ], times=1:28, ylevels=ylev,
                           absorb='Dead', tvarname='day')
    # P(not at home) =  1 - P(home); sum these probs to get E[days]
    mtud <- sum(1. - s1[, 'Home']) - sum(1. - s0[, 'Home'])
    diffmean[i] <- mtud
  }
  saveRDS(list(betas=betas, diffmean=diffmean), 'markov-boot.rds', compress='xz')
}

See how bootstrap treatment log ORs relate to differences in days unwell.

Code
ggfreqScatter(betas, diffmean,
              xlab='Log OR', ylab='Difference in Mean Days Unwell')
Figure 22.6: Relationship between bootstrap log ORs and differences in mean days unwell

Compute basic bootstrap 0.95 confidence interval for OR and differences in mean time

Code
# bootBCa is in the rms package and uses the boot package
clb <- exp(bootBCa(coef(f)['tx'], betas, seed=seed, n=npt, type='basic'))
clm <- bootBCa(dmtu, diffmean, seed=seed, n=npt, type='basic')
a   <- round(c(clb, clm), 3)[c(1,3,2,4)]
data.frame(Quantity=c('OR', 'Difference in mean days unwell'),
            Lower=a[1:2], Upper=a[3:4])
                        Quantity  Lower Upper
1                             OR  0.758 1.055
2 Difference in mean days unwell -2.336 0.470

22.3.7 Notes on Inference

  • Differences between treatments in mean time in state(s) is zero if and only if the treatment OR=1
    • note agreement in bootstrap estimates
    • will not necessarily be true if PO is relaxed for treatment
    • inference about any treatment effect is the same for all covariate settings that do not interact with treatment
    • \(\rightarrow p\)-values are the same for the two metrics, and Bayesian posterior probabilities are also identical
  • Bayesian posterior probabilities for mean time in state \(> \epsilon\), for \(\epsilon > 0\), will vary with covariate settings (sicker patients at baseline have more room to move)