| Type: | Package |
| Title: | Extended Joint Models for Longitudinal and Time-to-Event Data |
| Version: | 0.6-6 |
| Maintainer: | Dimitris Rizopoulos <d.rizopoulos@erasmusmc.nl> |
| Date: | 2026-11-18 |
| BugReports: | https://github.com/drizopoulos/JMbayes2/issues |
| Description: | Fit joint models for longitudinal and time-to-event data under the Bayesian approach. Multiple longitudinal outcomes of mixed type (continuous/categorical) and multiple event times (competing risks and multi-state processes) are accommodated. Rizopoulos (2012, ISBN:9781439872864). |
| Suggests: | lattice, knitr, rmarkdown, pkgdown |
| Encoding: | UTF-8 |
| Depends: | survival, nlme, GLMMadaptive, splines |
| Imports: | coda, Rcpp, parallel, parallelly, matrixStats, ggplot2, gridExtra, abind, MASS, survC1 |
| LinkingTo: | Rcpp, RcppArmadillo |
| LazyLoad: | yes |
| LazyData: | yes |
| License: | GPL (≥ 3) |
| URL: | https://drizopoulos.github.io/JMbayes2/ |
| Config/roxygen2/version: | 8.0.0 |
| NeedsCompilation: | yes |
| Packaged: | 2026-11-18 17:19:52 UTC; drizo |
| Author: | Dimitris Rizopoulos
|
| Repository: | CRAN |
| Date/Publication: | 2026-11-18 18:40:02 UTC |
Extended Joint Models for Longitudinal and Time-to-Event Data
Description
Fit joint models for longitudinal and time-to-event data under the Bayesian approach. Multiple longitudinal outcomes of mixed type (continuous/categorical) and multiple event times (competing risks and multi-state processes) are accommodated.
Details
| Package: | JMbayes2 |
| Type: | Package |
| Version: | 0.6-6 |
| Date: | 2026-11-18 |
| License: | GPL (>=3) |
This package fits joint models for longitudinal and time-to-event data. It can accommodate multiple longitudinal outcomes of different type (e.g., continuous, dichotomous, ordinal, counts), and assuming different distributions, i.e., Gaussian, Student's-t, Gamma, Beta, unit Lindley, censored Normal, Binomial, Poisson, Negative Binomial, and Beta-Binomial. For the event time process, right, left and interval censored data can be handled, while competing risks and multi-sate processes are also covered.
JMbayes2 fits joint models using Markov chain Monte Carlo algorithms implemented in C++. The package also offers several utility functions that can extract useful information from fitted joint models. The most important of those are included in the See also Section below.
Author(s)
Dimitris Rizopoulos, Grigorios Papageorgiou, Pedro Miranda-Afonso
Maintainer: Dimitris Rizopoulos <d.rizopoulos@erasmusmc.nl>
References
Rizopoulos, D. (2012). Joint Models for Longitudinal and Time-to-Event Data With Applications in R. Boca Raton: Chapman & Hall/CRC.
See Also
jm,
methods.jm,
coda_methods.jm
Predictions from Joint Models
Description
Predict method for object of class "jm".
Usage
## S3 method for class 'jm'
predict(object,
newdata = NULL, newdata2 = NULL, times = NULL,
process = c("longitudinal", "event"),
type_pred = c("response", "link"),
type = c("subject_specific", "mean_subject"),
control = NULL, ...)
## S3 method for class 'predict_jm'
plot(x, x2 = NULL, subject = 1, outcomes = 1,
fun_long = NULL, fun_event = NULL, CI_long = TRUE, CI_event = TRUE,
xlab = "Follow-up Time", ylab_long = NULL, ylab_event = "Cumulative Risk",
main = "", lwd_long = 2, lwd_event = 2, ylim_event = c(0, 1),
ylim_long_outcome_range = TRUE,
col_line_long = "#0000FF",
col_line_event = c("#FF0000", "#03BF3D", "#8000FF"), pch_points = 16,
col_points = "blue", cex_points = 1, fill_CI_long = "#0000FF4D",
fill_CI_event = c("#FF00004D", "#03BF3D4D", "#8000FF4D"), cex_xlab = 1,
cex_ylab_long = 1, cex_ylab_event = 1, cex_main = 1, cex_axis = 1,
col_axis = "black", pos_ylab_long = c(0.1, 2, 0.08), bg = "white",
...)
## S3 method for class 'jmList'
predict(object,
weights, newdata = NULL, newdata2 = NULL,
times = NULL, process = c("longitudinal", "event"),
type_pred = c("response", "link"),
type = c("subject_specific", "mean_subject"),
control = NULL, ...)
Arguments
object |
an object inheriting from class |
weights |
a numeric vector of model weights. |
newdata, newdata2 |
data.frames. |
times |
a numeric vector of future times to calculate predictions. |
process |
for which process to calculation predictions, for the longitudinal outcomes or the event times. |
type |
level of predictions; only relevant when |
type_pred |
type of predictions; options are |
control |
a named
.
|
x, x2 |
objects returned by |
subject |
when multiple subjects are included in the data.frames |
outcomes |
when multiple longitudinal outcomes are included in the data.frames |
fun_long, fun_event |
function to apply to the predictions for the longitudinal and event outcomes, respectively. When multiple longitudinal outcomes are plotted, |
CI_long, CI_event |
logical; should credible interval areas be plotted. |
xlab, ylab_long, ylab_event |
characture strings or a chracter vector for |
lwd_long, lwd_event, col_line_long, col_line_event, main, fill_CI_long, fill_CI_event, cex_xlab, cex_ylab_long, cex_ylab_event, cex_main, cex_axis, pch_points, col_points, cex_points, col_axis, bg |
graphical parameters; see |
pos_ylab_long |
controls the position of the y-axis labels when multiple longitudinal outcomes are plotted. |
ylim_event |
the |
ylim_long_outcome_range |
logical; if |
... |
aguments passed to control. |
Details
A detailed description of the methodology behind these predictions is given here: https://drizopoulos.github.io/JMbayes2/articles/Dynamic_Predictions.html.
Value
Method predict() returns a list or a data.frame (if return_newdata was set to TRUE) with the predictions.
Method plot() produces figures of the predictions from a single subject.
Author(s)
Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
See Also
Examples
# We fit a multivariate joint model
pbc2.id$status2 <- as.numeric(pbc2.id$status != 'alive')
CoxFit <- coxph(Surv(years, status2) ~ sex, data = pbc2.id)
fm1 <- lme(log(serBilir) ~ ns(year, 3) * sex, data = pbc2,
random = ~ ns(year, 3) | id, control = lmeControl(opt = 'optim'))
fm2 <- lme(prothrombin ~ ns(year, 2) * sex, data = pbc2,
random = ~ ns(year, 2) | id, control = lmeControl(opt = 'optim'))
fm3 <- mixed_model(ascites ~ year * sex, data = pbc2,
random = ~ year | id, family = binomial())
jointFit <- jm(CoxFit, list(fm1, fm2, fm3), time_var = "year", n_chains = 1L)
# we select the subject for whom we want to calculate predictions
# we use measurements up to follow-up year 3; we also set that the patients
# were alive up to this time point
t0 <- 3
ND <- pbc2[pbc2$id %in% c(2, 25), ]
ND <- ND[ND$year < t0, ]
ND$status2 <- 0
ND$years <- t0
# predictions for the longitudinal outcomes using newdata
predLong1 <- predict(jointFit, newdata = ND, return_newdata = TRUE)
# predictions for the longitudinal outcomes at future time points
# from year 3 to 10
predLong2 <- predict(jointFit, newdata = ND,
times = seq(t0, 10, length.out = 51),
return_newdata = TRUE)
# predictions for the event outcome at future time points
# from year 3 to 10
predSurv <- predict(jointFit, newdata = ND, process = "event",
times = seq(t0, 10, length.out = 51),
return_newdata = TRUE)
plot(predLong1)
# for subject 25, outcomes in reverse order
plot(predLong2, outcomes = 3:1, subject = 25)
# prediction for the event outcome
plot(predSurv)
# combined into one plot, the first longitudinal outcome and cumulative risk
plot(predLong2, predSurv, outcomes = 1)
# the first two longitudinal outcomes
plot(predLong1, predSurv, outcomes = 1:2)
# all three longitudinal outcomes, we display survival probabilities instead
# of cumulative risk, and we transform serum bilirubin to the original scale
plot(predLong2, predSurv, outcomes = 1:3, fun_event = function (x) 1 - x,
fun_long = list(exp, identity, identity),
ylab_event = "Survival Probabilities",
ylab_long = c("Serum Bilirubin", "Prothrombin", "Ascites"),
pos_ylab_long = c(1.9, 1.9, 0.08))
Didanosine versus Zalcitabine in HIV Patients
Description
A randomized clinical trial in which both longitudinal and survival data were collected to compare the efficacy and safety of two antiretroviral drugs in treating patients who had failed or were intolerant of zidovudine (AZT) therapy.
Format
A data frame with 1408 observations on the following 9 variables.
patientpatients identifier; in total there are 467 patients.
Timethe time to death or censoring.
deatha numeric vector with 0 denoting censoring and 1 death.
CD4the CD4 cells count.
obstimethe time points at which the CD4 cells count was recorded.
druga factor with levels
ddCdenoting zalcitabine andddIdenoting didanosine.gendera factor with levels
femaleandmale.prevOIa factor with levels
AIDSdenoting previous opportunistic infection (AIDS diagnosis) at study entry, andnoAIDSdenoting no previous infection.AZTa factor with levels
intoleranceandfailuredenoting AZT intolerance and AZT failure, respectively.
Note
The data frame aids.id contains the first CD4 cell count measurement for each patient. This data frame is used to
fit the survival model.
References
Goldman, A., Carlin, B., Crane, L., Launer, C., Korvick, J., Deyton, L. and Abrams, D. (1996) Response of CD4+ and clinical consequences to treatment using ddI or ddC in patients with advanced HIV infection. Journal of Acquired Immune Deficiency Syndromes and Human Retrovirology 11, 161–169.
Guo, X. and Carlin, B. (2004) Separate and joint modeling of longitudinal and event time data using standard computer packages. The American Statistician 58, 16–24.
Calibration Plot for Dynamic Predictions under Right-Censored Data
Description
Displays a calibration plot at a specified horizon time (Thoriz), using longitudinal information available up to a given starting time point (Tstart). The function supports both joint models and Cox proportional hazards models. The calibration_metrics() function calculates metrics for the accuracy of predictions: The ICI is the mean absolute difference between the observed and predicted probabilities, E50 is the median absolute difference, and E90 is the 90% percentile of the absolute differences.
Usage
calibration_plot(object, newdata, Tstart, ...)
## S3 method for class 'jm'
calibration_plot(object, newdata, Tstart, Thoriz = NULL,
Dt = NULL, df_ns = NULL, plot = TRUE,
col = "red", lty = 1, lwd = 1,
add_CI = TRUE, col_CI = "lightgrey",
add_density = TRUE, col_dens = "grey",
xlab = "Predicted Probabilities",
ylab = "Observed Probabilities", main = "", ...)
## S3 method for class 'coxph'
calibration_plot(object, newdata, Tstart, Thoriz = NULL,
Dt = NULL, df_ns = NULL, plot = TRUE,
col = "red", lty = 1, lwd = 1,
add_CI = TRUE, col_CI = "lightgrey",
add_density = TRUE, col_dens = "grey",
xlab = "Predicted Probabilities",
ylab = "Observed Probabilities", main = "", ...)
calibration_metrics(object, newdata, Tstart, Thoriz = NULL,
Dt = NULL, df_ns = NULL, ...)
Arguments
object |
an object inheriting from class |
newdata |
a data.frame that contains the longitudinal and covariate information for the subjects for which prediction of survival probabilities is required. If a |
Tstart |
numeric scalar denoting the time point up to which longitudinal information is to be used to derive predictions. |
Thoriz |
numeric scalar denoting the time point for which a prediction of the survival status is of interest; |
Dt |
numeric scalar denoting the length of the time interval of prediction; either |
df_ns |
the degrees of freedom for the natural cubic spline of the cloglog transformation of the predicted
probabilities used in the Cox model that assesses calibration. The default is 3 unless there are less than 25 events
in the interval ( |
plot |
logical; should a plot be produced. If |
add_CI |
logical; should 0.95 pointwise confidence intervals be added around the calibration line. |
col_CI |
character; the color of the shaded area representing the 0.95 pointwise confidence intervals around the calibration line. |
add_density |
logical; should the kernal density estimation of the predicted probabilities be superimposed in the calibration plot. |
col, lwd, lty, col_dens, xlab, ylab, main |
graphical parameters. |
... |
additional arguments passed to |
Value
If plot = TRUE (the default) a calibration plot is returned. Otherwise, a list with the following components is returned:
observed |
numeric vector with observed probabilities. |
predicted |
grid of probabilities used as x-axis in the calibration plot. |
pi_u_t |
numeric vector with predicted probabilities. |
obs_pi_u_t |
transformed predicted probabilities using the Cox model with the cloglog transformation. |
low |
lower bound of the 95% confidence interval for the observed probabilities. |
upp |
upper bound of the 95% confidence interval for the observed probabilities. |
For the calibration_metrics() function, a numeric vector with the following components is returned:
ICI |
numeric scalar denoting the mean absolute difference between the observed and predicted probabilities. |
E50 |
numeric scalar denoting the median absolute difference between the observed and predicted probabilities. |
E90 |
numeric scalar denoting the 90% percentile of absolute differences between the observed and predicted probabilities. |
Author(s)
Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
References
Rizopoulos, D. (2016). The R package JMbayes for fitting joint models for longitudinal and time-to-event data using MCMC. Journal of Statistical Software 72(7), 1–45. doi:10.18637/jss.v072.i07.
Rizopoulos, D. (2012) Joint Models for Longitudinal and Time-to-Event Data: with Applications in R. Boca Raton: Chapman and Hall/CRC.
Rizopoulos, D. (2011). Dynamic predictions and prospective accuracy in joint models for longitudinal and time-to-event data. Biometrics 67, 819–829.
Rizopoulos, D., Molenberghs, G. and Lesaffre, E.M.E.H. (2017). Dynamic predictions with time-dependent covariates in survival analysis using joint modeling and landmarking. Biometrical Journal 59, 1261–1276.
See Also
Examples
# We fit a multivariate joint model
pbc2.id$status2 <- as.numeric(pbc2.id$status != 'alive')
CoxFit <- coxph(Surv(years, status2) ~ sex, data = pbc2.id)
fm1 <- lme(log(serBilir) ~ ns(year, 3) * sex, data = pbc2,
random = ~ ns(year, 3) | id, control = lmeControl(opt = 'optim'))
jointFit <- jm(CoxFit, fm1, time_var = "year", n_chains = 1L)
# We use landmark time 4 and prediction horizon 3:
calibration_plot(jointFit, newdata = pbc2, Tstart = 4, Dt = 3, cores = 1L)
# Now the calibration metrics:
calibration_metrics(jointFit, pbc2, Tstart = 4, Thoriz = 7, cores = 1L)
Consensus Combination of Posterior Draws from Joint Model Fits
Description
This function combines posterior draws from multiple joint model fits into a single set of draws.
Usage
consensus(object, parm, method = c("union", "equal_weight", "var_weight"),
seed = 123L)
Arguments
object |
an object of class |
parm |
a character vector with the names of parameters to combine. These
must correspond to elements in |
method |
the consensus method used to combine draws.
|
seed |
an integer seed used for the within-slice random permutation step
(used by |
Value
An object of class "consensus_jm" with components:
methodthe selected method.
parmthe requested parameter(s) block(s).
n_splitsnumber of fits combined.
drawsnamed list of combined draw matrices (one per parameter block).
weightsfor
"equal_weight"and"var_weight", a named list of weight matrices.n_drawsnumber of combined draws per parameter block.
summarynamed list of summary matrices with
Mean,StDev,2.5%,97.5%, andP).seedseed used.
Author(s)
Pedro Miranda-Afonso p.mirandaafonso@erasmusmc.nl
Creating Training and Testing Datasets
Description
This is an auxiliar function that splits the data into folds for internal validation or Bootstrap methods.
Usage
create_folds(data, V = 5, id_var = "id",
method = c("CV", "Bootstrap"), strata = NULL, seed = 123L)
Arguments
data |
the data.frame to split in folds. |
V |
numeric scalar denoting the number of folds for cross-validation or the number of sample for the Bootstrap methods. |
id_var |
character string denoting the name of the subject id variable in |
method |
character string indicating which method to use to create the training and testing datasets in
|
strata |
character vector with the names of stratifying variables. |
seed |
integer denoting the seed. |
Value
A list with the following components:
training |
list containing training datasets. |
testing |
list containing testing datasets. |
Author(s)
Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
See Also
Examples
CVdats <- create_folds(pbc2, V = 5, id_var = "id")
CVdats
Transform Competing Risks Data in Long Format
Description
In a competing risks setting this function expands the data frame with a single row per subject to a data frame in the long format in which each subject has as many rows as the number of competing events.
Usage
crisk_setup(data, statusVar, censLevel,
nameStrata = "strata", nameStatus = "status2")
Arguments
data |
the data frame containing the competing risk data with a single row per subject. |
statusVar |
a character string denoting the name of the variable in
|
censLevel |
a character string or a scalar denoting the censoring level
in the |
nameStrata |
a character string denoting the variable that will be added
in the long version of |
nameStatus |
a character string denoting the variable that will be added
in the long version of |
Value
A data frame in the long format with multiple rows per subject.
Author(s)
Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
References
Rizopoulos, D. (2012) Joint Models for Longitudinal and Time-to-Event Data: with Applications in R. Boca Raton: Chapman and Hall/CRC.
Putter, H., Fiocco, M., and Geskus, R. (2007). Tutorial in biostatistics: Competing risks and multi-state models. Statistics in Medicine 26, 2389–2430.
Examples
head(crisk_setup(pbc2.id, "status", "alive"))
(Un)weighted Decision Curves for Dynamic Predictions under Left-Truncated and Right-Censored Data
Description
Computes estimates of the net benefit or (weighted) expected cost over a grid of decision thresholds at a specified horizon time (Thoriz), using longitudinal information available up to a given starting time point (Tstart). The function supports joint models, Cox proportional hazards models and predictions obtained from any method. It provides inverse probability weighting and model-based estimation methods. For the weighted expected cost, the beta family of weight functions has been implemented. The plot.decision_curves() method displays the decision curves, supporting multiple models or decision strategies in the same graphic.
Usage
decision_curves(object, ...)
## Default S3 method:
decision_curves(object, Time, event, LT_Time = NULL, Tstart,
decision_threshold_range = seq(0 + 1e-06, 1 - 1e-06, length.out = 51),
type = c("EC", "weightedEC", "NB"),
shape1 = NULL, shape2 = NULL, mod = NULL, interv = NULL, mass = 0.95,
Thoriz = NULL, Dt = NULL, type_weights = c("model-based", "IPCW"),
preds_MB = NULL, opt_interv = c(1, 500), ...)
## S3 method for class 'jm'
decision_curves(object, newdata, Tstart,
decision_threshold_range = seq(0 + 1e-06, 1 - 1e-06, length.out = 51),
type = c("EC", "weightedEC", "NB"),
shape1 = NULL, shape2 = NULL, mod = NULL, interv = NULL, mass = 0.95,
Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"), opt_interv = c(1, 500), ...)
## S3 method for class 'coxph'
decision_curves(object, newdata, Tstart,
decision_threshold_range = seq(0 + 1e-06, 1 - 1e-06, length.out = 51),
type = c("EC", "weightedEC", "NB"),
shape1 = NULL, shape2 = NULL, mod = NULL, interv = NULL, mass = 0.95,
Thoriz = NULL, Dt = NULL, type_weights = c("model-based", "IPCW"),
opt_interv = c(1, 500), ...)
## S3 method for class 'decision_curves'
plot(x, ...,
col = c(rep(1, length(objects)), "yellow3", "red"),
lty = c(seq_along(objects), 1, 1),
lwd = rep(1, length(objects) + 2),
xlab = "Decision threshold",
ylab = "Expected cost",
main = "",
ylim = NULL, xlim = NULL,
legend_loc = "topright", legend_cex = 0.8,
legend_names = c(paste("Model", seq_along(objects)), "Treat all", "Treat none"),
weight_function = TRUE,
weight_function_txt = TRUE,
weight_function_col = adjustcolor("black", alpha.f = 0.6))
Arguments
object |
an object inheriting from class |
newdata |
a data.frame that contains the longitudinal and covariate information for the subjects for which prediction of survival probabilities is required. If a |
Tstart |
numeric scalar denoting the time point up to which longitudinal information is to be used to derive predictions. |
decision_threshold_range |
a numeric vector containing the grid of decision threshdolds to be used in the decision curves. Default is |
Time, event, LT_Time |
numeric vectors that must be specified when using the default method to compute the metric by directly using a vector of predictions, observed times ( |
type |
character string denoting the type of decision curve. Options are expected cost ("EC"; default), weighted expected cost ("weightedEC"; including IWEC estimates) and net benefit ("NB"). |
shape1, shape2 |
numeric scalars greater or equal to 0 denoting the shape parameteres for the beta family of weight functions (see below for details). |
mod, mass, interv |
two numeric scalars between 0 and 1 and a numeric vector with two scalars between 0 and 1, denoting the mode of the weight function and the mass (default is 95%) to be allocated within the interval defined by the two values in the numeric vector. These arguments can be used to compute the shape parameters in the weighted decision curves. See below for details. |
Thoriz |
numeric scalar denoting the time point for which a prediction of the survival status is of interest; |
Dt |
numeric scalar denoting the length of the time interval of prediction; either |
type_weights |
character string denoting the type of weights to use to account for censorting. Options are model-based (default) and inverse probability weighting (using the Kaplan-Meier estimate of the censoring distribution, and adjusting for left truncation if necessary). |
preds_MB |
a numeric vector containing the model-based weights to be used for the individuals censored within ( |
opt_interv |
a numeric vector containing the end-points of the interval to be searched for the root. This argumentis used when |
x |
an object inhereting from class |
... |
additional arguments passed to |
col, lwd, lty, xlab, ylab, xlim, ylim, main |
graphical parameters. |
legend_loc, legend_cex, legend_names |
graphical parameters for the legend displayed in the decision curve. |
weight_function, weight_function_txt, weight_function_col |
graphical parameters for the weight function displayed in the decision curve when types |
Details
The beta family of weight functions is consdiered for the weighted expectec cost. It is defined by the two-parameter form w(c;\text{shape1}, \text{shape2})=c^{\text{shape1}-1}(1-c)^{\text{shape2}-1}/B(\text{shape1}, \text{shape2}), where \text{shape1}, \text{shape2}\geq 0 are shape parameters and B(\text{shape1},\text{shape2})=1 if \text{shape1}=\text{shape2}=0, and otherwise denotes the beta function.
When mod, mass and interv are provided we compute the shape parameters shape1 and shape2 by solving the system consisting of the two equations: \text{mod}=\frac{\text{shape1} - 1}{\text{shape1} + \text{shape2} - 2} and \text{Pr}(X \in \text{interv}) = \text{mass}, where X follows a beta distribution with shape parameters shape1 and shape2. To solve this system, the uniroot() function is internally used. The user can change the interval argument of the uniroot() function using the opt_interv argument.
Value
A list of class decision_curves with components:
metric_c |
a list of three components, each containing a numeric vector representing the net benefit or (weighted) expected cost for the prediction model, along with the default strategies of treating all patients or no patients, respectively. |
newdata |
a data.frame containing the exact dataset used to compute the evaluated dynamic predictions. |
nr |
a numeric scalar denoting the number of subjects at risk at time |
nint |
a numeric scalar denoting the number of subjects with an event in ( |
ncens |
a numeric scalar denoting the number of subjects with a censored time in ( |
Tstart |
a copy of the |
Thoriz |
a copy of the |
type |
a copy of the |
shape1, shape2 |
a copy of the arguments |
decision_threshold_range |
a copy of the |
iwecs |
a numeric vector containing the IWEC estimates, in case |
type_weights |
a copy of the |
classObject |
the class of |
nameObject |
the name of |
Author(s)
Arnau Garcia-Fernandez a.garciafernandez@erasmusmc.nl, Pedro Miranda-Afonso p.mirandaafonso@erasmusmc.nl and Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
References
Vickers, Andrew J and Elkin, Elena B (2006). Decision curve analysis: a novel method for evaluating prediction models. Medical Decision Making 26, 565–574.
See Also
tvIWEC, tvNB, tvEC, predict, jm
Examples
# We fit a multivariate joint model
pbc2.id$status2 <- as.numeric(pbc2.id$status != 'alive')
CoxFit <- coxph(Surv(years, status2) ~ sex, data = pbc2.id)
fm1 <- lme(log(serBilir) ~ ns(year, 3) * sex, data = pbc2,
random = ~ ns(year, 3) | id, control = lmeControl(opt = 'optim'))
fm2 <- lme(prothrombin ~ ns(year, 2) * sex, data = pbc2,
random = ~ ns(year, 2) | id, control = lmeControl(opt = 'optim'))
jointFit <- jm(CoxFit, list(fm1, fm2), time_var = "year", n_chains = 1L)
# Classic decision curve using net benefit.
# We use landmark time 4 and prediction horizon 3.
dc_NB <- decision_curves(jointFit, newdata = pbc2, Tstart = 4, Dt = 3,
type = "NB", cores = 1L)
plot(dc_NB)
# Considering the Cox model, the IPW approach for estimation and
# shape parameters 12 and 38, we display the decision curve for the expected
# cost, with the weight function at the top part of the plot
dc_EC <- decision_curves(CoxFit, newdata = pbc2.id, Tstart = 2, Thoriz = 6,
shape1 = 12, shape2 = 38, type_weights = "IPCW",
cores = 1L)
plot(dc_EC, legend_names = c("Cox model", "Treat all strategy", "Treat none strategy"))
# We now display the weighted decision curve. The weight function is such that
# the mode is 0.2, the interval of interest for the decision thresholds is
# (0.1, 0.3) and the mass to be allocated within the interval is 0.85
dc_wEC <- decision_curves(jointFit, newdata = pbc2, Tstart = 4, Dt = 3,
mod = 0.2, interv = c(0.1, 0.3), mass = 0.8,
type = "weightedEC", cores = 1L)
plot(dc_wEC,
legend_names = c("Joint model", "Treat all", "Treat none"),
col = c("black", "lightblue3", "brown2"),
lty = c(1, 2, 2))
Joint Models for Longitudinal and Time-to-Event Data
Description
Fits multivariate joint models for longitudinal and time-to-event data.
Usage
jm(Surv_object, Mixed_objects, time_var, recurrent = FALSE,
functional_forms = NULL, which_independent = NULL,
base_hazard = NULL, data_Surv = NULL, id_var = NULL,
priors = NULL, control = NULL, ...)
value(x, IE_time = NULL)
coefs(x, zero_ind = NULL, IE_time = NULL)
slope(x, eps = 0.001, direction = "both", IE_time = NULL)
velocity(x, eps = 0.001, direction = "both", IE_time = NULL)
acceleration(x, IE_time = NULL)
area(x, time_window = NULL, IE_time = NULL)
Delta(x, time_window = NULL, standardise = TRUE, IE_time = NULL)
vexpit(x)
Dexpit(x)
vexp(x)
Dexp(x)
vabs(x)
vlog(x)
vlog2(x)
vlog10(x)
vsqrt(x)
poly2(x)
poly3(x)
poly4(x)
tv(x, knots = NULL, ord = 2L)
Arguments
Surv_object |
an object:
|
Mixed_objects |
a
|
time_var |
a |
recurrent |
a |
functional_forms |
a |
which_independent |
a numeric indicator matrix denoting which outcomes are independent. It can also be the character string |
base_hazard |
a |
data_Surv |
the |
id_var |
a |
priors |
a named
|
control |
a list of control values with components:
|
x |
a numeric input variable. |
knots |
a numeric vector of knots. |
ord |
an integer denoting the order of the spline. |
zero_ind |
a list with integer vectors indicating which coefficients are set to zero in the calculation of the value term. This can be used to include for example only the random intercept; default is |
eps |
numeric scalar denoting the step-size for the finite difference approximation. |
direction |
character string for the direction of the numerical derivative, options are |
time_window |
numeric scalar controlling the time window used by the |
standardise |
|
IE_time |
a |
... |
arguments passed to |
Details
The mathematical details regarding the definition of the multivariate joint model, and the capabilities of the package can be found in the vignette in the doc directory.
Notes:
The ordering of the subjects in the datasets used to fit the mixed and Cox regression models needs to be the same.
The units of the time variables in the mixed and Cox models need to be the same.
Value
A list of class jm with components:
mcmc |
a |
acc_rates |
a |
logLik |
a |
mlogLik |
a |
running_time |
an object of class |
statistics |
a |
fit_stats |
a |
model_data |
a |
model_info |
a |
initial_values |
a |
control |
a copy of the |
priors |
a copy of the |
call |
the matched call. |
Author(s)
Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
See Also
Examples
################################################################################
##############################################
# Univariate joint model for serum bilirubin #
# 1 continuous outcome #
##############################################
# [1] Fit the mixed model using lme().
fm1 <- lme(fixed = log(serBilir) ~ year * sex + I(year^2) +
age + prothrombin, random = ~ year | id, data = pbc2)
# [2] Fit a Cox model, specifying the baseline covariates to be included in the
# joint model.
fCox1 <- coxph(Surv(years, status2) ~ drug + age, data = pbc2.id)
# [3] The basic joint model is fitted using a call to jm() i.e.,
joint_model_fit_1 <- jm(fCox1, fm1, time_var = "year",
n_chains = 1L, n_iter = 11000L, n_burnin = 1000L)
summary(joint_model_fit_1)
traceplot(joint_model_fit_1)
################################################################################
##########################################################################
# Multivariate joint model for serum bilirubin, hepatomegaly and ascites #
# 1 continuous outcome, 2 categorical outcomes #
##########################################################################
# [1] Fit the mixed-effects models using lme() for continuous
# outcomes and mixed_model() for categorical outcomes.
fm1 <- lme(fixed = log(serBilir) ~ year * sex,
random = ~ year | id, data = pbc2)
fm2 <- mixed_model(hepatomegaly ~ sex + age + year, data = pbc2,
random = ~ year | id, family = binomial())
fm3 <- mixed_model(ascites ~ year + age, data = pbc2,
random = ~ year | id, family = binomial())
# [2] Save all the fitted mixed-effects models in a list.
Mixed <- list(fm1, fm2, fm3)
# [3] Fit a Cox model, specifying the baseline covariates to be included in the
# joint model.
fCox1 <- coxph(Surv(years, status2) ~ drug + age, data = pbc2.id)
# [4] The joint model is fitted using a call to jm() i.e.,
joint_model_fit_2 <- jm(fCox1, Mixed, time_var = "year",
n_chains = 1L, n_iter = 11000L, n_burnin = 1000L)
summary(joint_model_fit_2)
traceplot(joint_model_fit_2)
################################################################################
######################
# Slope & Area Terms #
######################
# We extend model 'joint_model_fit_2' by including the value and slope term for
# bilirubin, the area term for hepatomegaly (in the log-odds scale), and the
# value and area term for spiders (in the log-odds scale).
# To include these terms into the model, we specify the 'functional_forms'
# argument. This should be a list of right side formulas. Each component of the
# list should have as name the name of the corresponding outcome variable. In
# the right side formula we specify the functional form of the association using
# functions 'value()', 'slope()' and 'area()'.
# Notes: (1) For terms not specified in the 'functional_forms' list, the default
# value functional form is used.
# [1] Fit the mixed-effects models using lme() for continuous outcomes
# and mixed_model() for categorical outcomes.
fm1 <- lme(fixed = log(serBilir) ~ year * sex, random = ~ year | id, data = pbc2)
fm2 <- mixed_model(hepatomegaly ~ sex + age + year, data = pbc2,
random = ~ year | id, family = binomial())
fm3 <- mixed_model(ascites ~ year + age, data = pbc2,
random = ~ year | id, family = binomial())
# [2] Save all the fitted mixed-effects models in a list.
Mixed <- list(fm1, fm2, fm3)
# [3] Fit a Cox model, specifying the baseline covariates to be included in the
# joint model.
fCox1 <- coxph(Surv(years, status2) ~ drug + age, data = pbc2.id)
# [4] Specify the list of formulas to be passed to the functional_forms argument
# of jm().
fForms <- list("log(serBilir)" = ~ value(log(serBilir)) + slope(log(serBilir)),
"hepatomegaly" = ~ area(hepatomegaly),
"ascites" = ~ value(ascites) + area(ascites))
# [5] The joint model is fitted using a call to jm() and passing the list
# to the functional_forms argument.
joint_model_fit_2 <- jm(fCox1, Mixed, time_var = "year",
functional_forms = fForms, n_chains = 1L,
n_iter = 11000L, n_burnin = 1000L)
summary(joint_model_fit_2)
Various Methods for Standard Generics
Description
Methods for object of class "jm" for standard generic functions.
Usage
coef(object, ...)
## S3 method for class 'jm'
coef(object, ...)
fixef(object, ...)
## S3 method for class 'jm'
fixef(object, outcome = Inf, ...)
ranef(object, ...)
## S3 method for class 'jm'
ranef(object, outcome = Inf, post_vars = FALSE, ...)
terms(x, ...)
## S3 method for class 'jm'
terms(x, process = c("longitudinal", "event"),
type = c("fixed", "random"), ...)
model.frame(formula, ...)
## S3 method for class 'jm'
model.frame(formula, process = c("longitudinal", "event"),
type = c("fixed", "random"), ...)
model.matrix(object, ...)
## S3 method for class 'jm'
model.matrix(object, ...)
family(object, ...)
## S3 method for class 'jm'
family(object, ...)
compare_jm(..., type = c("marginal", "conditional"),
order = c("WAIC", "DIC", "LPML", "none"))
Arguments
object, x, formula |
object inheriting from class |
outcome |
the index of the linear mixed submodel to extract the estimated fixed effects. If greater than the total number of submodels, extracts from all of them. |
post_vars |
logical; if |
process |
which submodel(s) to extract the terms:
|
type |
in
in
|
... |
further arguments; currently, none is used. |
order |
which criteria use to sort the models in the output. |
Details
coef()Extracts estimated fixed effects for the event process from a fitted joint model.
fixef()Extracts estimated fixed effects for the longitudinal processes from a fitted joint model.
ranef()Extracts estimated random effects from a fitted joint model.
terms()Extracts the terms object(s) from a fitted joint model.
model.frame()Creates the model frame from a fitted joint model.
model.matrix()Creates the design matrices for linear mixed submodels from a fitted joint model.
family()Extracts the error distribution and link function used in the linear mixed submodel(s) from a fitted joint model.
compare_jm()Compares two or more fitted joint models using the criteria WAIC, DIC, and LPML.
Value
coef()a list with the elements:
-
gammas: estimated baseline fixed effects, and -
association: estimated association parameters.
-
fixef()a numeric vector of the estimated fixed effects for the
outcomeselected. If theoutcomeis greater than the number of linear mixed submodels, it returns a list of numeric vectors for all outcomes.ranef()a numeric matrix with rows denoting the individuals and columns the random effects. If
postVar = TRUE, the numeric matrix has the extra attribute "postVar".terms()if
process = "longitudinal", a list of the terms object(s) for the linear mixed model(s).
ifprocess = "event", the terms object for the survival model.model.frame()if
process = "longitudinal", a list of the model frames used in the linear mixed model(s).
ifprocess = "event", the model frame used in the survival model.model.matrix()a list of the design matrix(ces) for the linear mixed submodel(s).
family()a list of
familyobjects.compare_jm()a list with the elements:
-
table: a table with the criteria calculated for each joint model, and -
type: the log-likelihood function used to calculate the criteria.
-
Author(s)
Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
See Also
Examples
# linear mixed model fits
fit_lme1 <- lme(log(serBilir) ~ year:sex + age,
random = ~ year | id, data = pbc2)
fit_lme2 <- lme(prothrombin ~ sex,
random = ~ year | id, data = pbc2)
# cox model fit
fit_cox <- coxph(Surv(years, status2) ~ age, data = pbc2.id)
# joint model fit
fit_jm <- jm(fit_cox, list(fit_lme1, fit_lme2), time_var = "year",
n_chains = 1L, n_iter = 11000L, n_burnin = 1000L)
# coef(): fixed effects for the event process
coef(fit_jm)
# fixef(): fixed effects for the first linear mixed submodel
fixef(fit_jm, outcome = 1)
# ranef(): random effects from all linear mixed submodels
head(ranef(fit_jm))
# terms(): random effects terms for the first linear mixed submodel
terms(fit_jm, process = "longitudinal", type = "random")[[1]]
# mode.frame(): model frame for the fixed effects in the second
# linear mixed submodel
head(model.frame(fit_jm, process = "longitudinal", type = "fixed")[[2]])
# model.matrix(): fixed effects design matrix for the first linear
# mixed submodel
head(model.matrix(fit_jm)[[1]])
# family(): family objects from both linear mixed submodels
family(fit_jm)
# compare_jm(): compare two fitted joint models
fit_lme1b <- lme(log(serBilir) ~ 1,
random = ~ year | id, data = pbc2)
fit_jm2 <- jm(fit_cox, list(fit_lme1b, fit_lme2), time_var = "year",
n_chains = 1L, n_iter = 11000L, n_burnin = 1000L)
compare_jm(fit_jm, fit_jm2)
Various Methods for Functions from the coda Package
Description
Methods for an object of class "jm" for diagnostic functions.
Usage
traceplot(object, ...)
## S3 method for class 'jm'
traceplot(object,
parm = c("all", "betas", "sigmas", "D", "bs_gammas",
"tau_bs_gammas", "gammas", "alphas"), ...)
ggtraceplot(object, ...)
## S3 method for class 'jm'
ggtraceplot(object,
parm = c("all", "betas", "sigmas", "D", "bs_gammas",
"tau_bs_gammas", "gammas", "alphas"),
linewidth = 1, alpha = 0.8,
theme = c('standard', 'catalog', 'metro',
'pastel', 'beach', 'moonlight', 'goo', 'sunset', 'custom'),
grid = FALSE, gridrows = 3, gridcols = 1, custom_theme = NULL, ...)
gelman_diag(object, ...)
## S3 method for class 'jm'
gelman_diag(object,
parm = c("all", "betas", "sigmas", "D", "bs_gammas",
"tau_bs_gammas", "gammas", "alphas"), ...)
densplot(object, ...)
## S3 method for class 'jm'
densplot(object,
parm = c("all", "betas", "sigmas", "D", "bs_gammas",
"tau_bs_gammas", "gammas", "alphas"), ...)
ggdensityplot(object, ...)
## S3 method for class 'jm'
ggdensityplot(object,
parm = c("all", "betas", "sigmas", "D", "bs_gammas",
"tau_bs_gammas", "gammas", "alphas"),
linewidth = 1, alpha = 0.6,
theme = c('standard', 'catalog', 'metro', 'pastel',
'beach', 'moonlight', 'goo', 'sunset', 'custom'),
grid = FALSE, gridrows = 3, gridcols = 1, custom_theme = NULL, ...)
cumuplot(object, ...)
## S3 method for class 'jm'
cumuplot(object,
parm = c("all", "betas", "sigmas", "D", "bs_gammas",
"tau_bs_gammas", "gammas", "alphas"), ...)
Arguments
object |
an object inheriting from class |
parm |
a character string specifying which parameters of the joint model to plot. Possible options are |
linewidth |
the width of the traceplot line in mm. Defaults to 1. |
alpha |
the opacity level of the traceplot line. Defaults to 0.8. |
theme |
a character string specifying the color theme to be used. Possible options are |
grid |
logical; defaults to |
gridrows |
number of rows per page for the grid. Only relevant when using |
gridcols |
number of columns per page for the grid. Only relevant when using |
custom_theme |
A named character vector with elements equal to the number of chains ( |
... |
further arguments passed to the corresponding function from the coda package. |
Value
traceplot()Plots the evolution of the estimated parameter vs. iterations in a fitted joint model.
ggtraceplot()Plots the evolution of the estimated parameter vs. iterations in a fitted joint model using ggplot2.
gelman_diag()Calculates the potential scale reduction factor for the estimated parameters in a fitted joint model, together with the upper confidence limits.
densplot()Plots the density estimate for the estimated parameters in a fitted joint model.
ggdensityplot()Plots the evolution of the estimated parameter vs. iterations in a fitted joint model using ggplot2.
cumuplot()Plots the evolution of the sample quantiles vs. iterations in a fitted joint model.
Author(s)
Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
See Also
Examples
# linear mixed model fits
fit_lme1 <- lme(log(serBilir) ~ year:sex + age,
random = ~ year | id, data = pbc2)
fit_lme2 <- lme(prothrombin ~ sex,
random = ~ year | id, data = pbc2)
# cox model fit
fit_cox <- coxph(Surv(years, status2) ~ age, data = pbc2.id)
# joint model fit
fit_jm <- jm(fit_cox, list(fit_lme1, fit_lme2), time_var = "year", n_chains = 1L)
# trace plot for the fixed effects in the linear mixed submodels
traceplot(fit_jm, parm = "betas")
# density plot for the fixed effects in the linear mixed submodels
densplot(fit_jm, parm = "betas")
# cumulative quantile plot for the fixed effects in the linear mixed submodels
cumuplot(fit_jm, parm = "betas")
# trace plot for the fixed effects in the linear mixed submodels
ggtraceplot(fit_jm, parm = "betas")
ggtraceplot(fit_jm, parm = "betas", grid = TRUE)
ggtraceplot(fit_jm, parm = "betas", custom_theme = c('1' = 'black'))
# trace plot for the fixed effects in the linear mixed submodels
ggdensityplot(fit_jm, parm = "betas")
ggdensityplot(fit_jm, parm = "betas", grid = TRUE)
ggdensityplot(fit_jm, parm = "betas", custom_theme = c('1' = 'black'))
Slice-aware model fitting generics
Description
These functions are S3 generics exported by JMbayes2 to enable method dispatch
on the class of the data argument. When data is a "sliced_data"
object (as produced by slicer), the corresponding slice-wise fitting
methods are used.
Usage
lme(fixed, data, ...)
coxph(formula, data, ...)
mixed_model(fixed, data, ...)
Arguments
fixed |
For |
formula |
For |
data |
A data frame (default methods) or a |
... |
Further arguments passed to the underlying model-fitting functions.
For slice-wise methods, additional arguments include |
Details
When data is a regular data frame, the default methods call
nlme::lme(), survival::coxph(), and GLMMadaptive::mixed_model(),
respectively.
When data is a "sliced_data" object, the corresponding *.sliced_data
methods fit the requested model independently within each slice and return a list of
fits (one per slice).
Note
JMbayes2 exports S3 generics lme(), coxph(), and mixed_model()
to enable dispatch on "sliced_data". When JMbayes2 is attached, these names
mask nlme::lme, survival::coxph, and GLMMadaptive::mixed_model.
Use the pkg::fun form to call the original functions.
See Also
slicer, nlme::lme, survival::coxph, GLMMadaptive::mixed_model.
Examples
## Not run:
slc <- slicer(n_slices = 2, id_var = "id", data_long = pbc2, data_surv = pbc2.id)
n_cores <- max(parallel::detectCores() - 1L, 1L)
lme_fit <- lme(fixed = log(serBilir) ~ year * sex,
data = slc$long,
random = ~ year | id,
cores = n_cores)
cox_fit <- coxph(formula = Surv(years, status2) ~ sex,
data = slc$surv,
cores = n_cores)
mxm_fit <- mixed_model(fixed = ascites ~ year + sex,
data = slc$long,
random = ~ year | id,
family = binomial(),
cores = n_cores)
## End(Not run)
Mayo Clinic Primary Biliary Cirrhosis Data
Description
Follow up of 312 randomised patients with primary biliary cirrhosis, a rare autoimmune liver disease, at Mayo Clinic.
Format
A data frame with 1945 observations on the following 20 variables.
idpatients identifier; in total there are 312 patients.
yearsnumber of years between registration and the earlier of death, transplantion, or study analysis time.
statusa factor with levels
alive,transplantedanddead.druga factor with levels
placeboandD-penicil.ageat registration in years.
sexa factor with levels
maleandfemale.yearnumber of years between enrollment and this visit date, remaining values on the line of data refer to this visit.
ascitesa factor with levels
NoandYes.hepatomegalya factor with levels
NoandYes.spidersa factor with levels
NoandYes.edemaa factor with levels
No edema(i.e., no edema and no diuretic therapy for edema),edema no diuretics(i.e., edema present without diuretics, or edema resolved by diuretics), andedema despite diuretics(i.e., edema despite diuretic therapy).serBilirserum bilirubin in mg/dl.
serCholserum cholesterol in mg/dl.
albuminalbumin in g/dl.
alkalinealkaline phosphatase in U/liter.
SGOTSGOT in U/ml.
plateletsplatelets per cubic ml / 1000.
prothrombinprothrombin time in seconds.
histologichistologic stage of disease.
status2a numeric vector with the value 1 denoting if the patient was dead, and 0 if the patient was alive or transplanted.
Note
The data frame pbc2.id contains the first measurement for each patient. This data frame is used to
fit the survival model.
References
Fleming, T. and Harrington, D. (1991) Counting Processes and Survival Analysis. Wiley, New York.
Therneau, T. and Grambsch, P. (2000) Modeling Survival Data: Extending the Cox Model. Springer-Verlag, New York.
Posterior Predictive Checks for Joint Models
Description
It computes various posterior predictive checks for joint models.
Usage
ppcheck(object, nsim = 40L, newdata = NULL, seed = 123L,
process = c("longitudinal", "event", "joint"),
type = c("ecdf", "average-evolution", "variance-function",
"variogram", "surv-uniform"),
CI_ecdf = c("none", "binomial", "Dvoretzky-Kiefer-Wolfowitz"), CI_loess = FALSE,
outcomes = Inf, percentiles = c(0.025, 0.975),
random_effects = c("posterior_means", "mcmc", "prior"),
params_mcmc = NULL, Fforms_fun = NULL, plot = TRUE, add_legend = TRUE,
pos_legend = c("bottomright", "right"), main = "", xlab = NULL,
ylab = NULL, col_obs = "black", col_rep = "lightgrey", lty_obs = 1,
lty_rep = 1, lwd_obs = 1.5, lwd_rep = 1, line_main = NA,
cex.main = 1.2, ylim = NULL, ...)
Arguments
object |
an object inheriting from class |
nsim |
a numeric scalar denoting the number of replicated data. |
newdata |
a data.frame based on which to simulate replicated data. Relevant for cross-validated posterior predictive checks. |
seed |
the seed to use. |
process |
a character string indicating for which process to do the checks. |
type |
a character string indicating the type of checks. The default |
CI_ecdf |
character string indicating the type of confidence interval for the emprical distribution function. |
CI_loess |
logical; if |
outcomes |
a numeric vector of indices indicating for which longitudinal outcomes to do the checks.
The deault value |
percentiles |
a numeric vector of length two indicating the percentiles of the observed data to use when depicting the checks. |
random_effects |
a character string indicating what to do with the random effects. |
params_mcmc |
a list with an MCMC sample of the model parameters. |
Fforms_fun |
a function that calculates the functional forms. |
plot |
logical; if |
add_legend |
logical; if |
pos_legend |
character string indicating the position of the legend. |
main, xlab, ylab, col_obs, col_rep, lty_obs, lty_rep, lwd_obs, lwd_rep, line_main, cex.main, ylim |
graphical parameters. |
... |
extra argument passed to |
Value
a figure with the checks.
Author(s)
Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
Examples
# Cox model for the composite event death or transplantation
pbc2.id$status2 <- as.numeric(pbc2.id$status != 'alive')
pbc2$status2 <- as.numeric(pbc2$status != 'alive')
CoxFit <- coxph(Surv(years, status2) ~ sex, data = pbc2.id)
# a linear mixed model for log serum bilirubin
fm1 <- lme(log(serBilir) ~ ns(year, 3) * sex, data = pbc2,
random = list(id = pdDiag(~ ns(year, 3))))
# the joint model
jointFit <- jm(CoxFit, fm1, time_var = "year", save_random_effects = TRUE)
ppcheck(jointFit)
FF <- function (t, betas, bi, data) {
sex <- as.numeric(data$sex == "female")
NS <- ns(t, k = c(0.9911, 3.9863), B = c(0, 14.10579))
X <- cbind(1, NS, sex, NS * sex)
Z <- cbind(1, NS)
eta <- c(X %*% betas[[1]]) + rowSums(Z * bi)
cbind(eta)
}
ppcheck(jointFit, process = "event", Fforms_fun = FF)
Prednisone versus Placebo in Liver Cirrhosis Patients
Description
A randomized trial on 488 liver cirrhosis patients.
Format
Two data frames with the following variables.
idpatients identifier; in total there are 467 patients.
proprothrobin measurements.
timefor data frame
prothrothe time points at which the prothrobin measurements were taken; for data frameprothrosthe time to death or censoring.deatha numeric vector with 0 denoting censoring and 1 death.
treatrandomized treatment; a factor with levels "placebo" and "prednisone".
References
Andersen, P. K., Borgan, O., Gill, R. D. and Keiding, N. (1993). Statistical Models Based on Counting Processes. New York: Springer.
Combine Recurring and Terminal Event Data in Long Format
Description
This function combines two data frames, the recurring-event and terminal-event/competing-risks datasets, into one. Each subject has as many rows in the new data frame as the number of recurrent risk periods plus one for each terminal event/competing risk.
Usage
rc_setup(rc_data, trm_data,
idVar = "id", statusVar = "status",
startVar = "start", stopVar = "stop",
trm_censLevel,
nameStrata = "strata", nameStatus = "status")
Arguments
rc_data |
the data frame containing the recurring-event data with multiple rows per subject. |
trm_data |
the data frame containing the terminal-event/competing-risks data with a single row per subject. |
idVar |
a character scalar denoting the name of the variable in
|
statusVar |
a character string denoting the name of the variable in
|
startVar |
a character string denoting the name of the variable in
|
stopVar |
a character string denoting the name of the variable in
|
trm_censLevel |
a character string or a scalar denoting the censoring
level in the statusVar variable of |
nameStrata |
a character string denoting the variable that will be added
in the long version of |
nameStatus |
a character string denoting the variable that will be added
in the long version of |
Value
A data frame in the long format with multiple rows per subject.
Author(s)
Pedro Miranda-Afonso p.mirandaafonso@erasmusmc.nl
Split Longitudinal and Survival Data into Subject-level Samples
Description
This function partitions a longitudinal dataset and a survival dataset at the subject level, returning two lists of sliced datasets for model fitting in parallel or series.
Usage
slicer(n_slices, id_var, data_long, data_surv, seed = 123L)
Arguments
n_slices |
an integer scalar giving the number of data slices (subsamples) to create. |
id_var |
a character scalar with the name of the subject identifier
variable in both |
data_long |
a data frame containing the longitudinal measurements. |
data_surv |
a data frame containing the survival (time-to-event) information. |
seed |
an integer seed used to randomize the assignment of subject IDs to slices. |
Value
A list with two components:
longa list of length
n_sliceswith class"sliced_data". Each element is a data frame containing the longitudinal rows for the subjects assigned to that slice.surva list of length
n_sliceswith class"sliced_data". Each element a data frame containing the survival rows for the subjects assigned to that slice.
Author(s)
Pedro Miranda-Afonso p.mirandaafonso@erasmusmc.nl
Examples
data(pbc2, package = "JMbayes2")
data(pbc2.id, package = "JMbayes2")
pbc2_slc <- slicer(n_slices = 2, id_var = "id", data_long = pbc2,
data_surv = pbc2.id, seed = 123L)
length(pbc2_slc$long) # 2
length(pbc2_slc$surv) # 2
Area Under the Receiver Operating Characteristic Curve (AUC) for Dynamic Predictions under Left-Truncated and Right-Censored Data
Description
Computes estimates of the AUC at a specified horizon time (Thoriz), using longitudinal information available up to a given starting time point (Tstart). The function supports both joint models and Cox proportional hazards models, and provides inverse probability weighting and model-based estimation methods.
Usage
tvAUC(object, newdata, Tstart, ...)
## S3 method for class 'jm'
tvAUC(object, newdata, Tstart, Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"), ...)
## S3 method for class 'coxph'
tvAUC(object, newdata, Tstart, Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"), ...)
Arguments
object |
an object inheriting from class |
newdata |
a data.frame that contains the longitudinal and covariate information for the subjects for which prediction of survival probabilities is required. If a |
Tstart |
numeric scalar denoting the time point up to which longitudinal information is to be used to derive predictions. |
Thoriz |
numeric scalar denoting the time point for which a prediction of the survival status is of interest; |
Dt |
numeric scalar denoting the length of the time interval of prediction; either |
type_weights |
character string denoting the type of weights to use to account for censorting. Options are model-based (default) and inverse probability weighting (using the Kaplan-Meier estimate of the censoring distribution, and adjusting for left truncation if necessary). |
... |
additional arguments passed to |
Value
A list of class tvAUC with components:
auc |
a numeric scalar denoting the estimated AUC. |
nr |
a numeric scalar denoting the number of subjects at risk at time |
nint |
a numeric scalar denoting the number of subjects with an event in ( |
ncens |
a numeric scalar denoting the number of subjects with a censored time in ( |
Tstart |
a copy of the |
Thoriz |
a copy of the |
type_weights |
a copy of the |
LT_MS |
a logical that is |
classObject |
the class of |
nameObject |
the name of |
Author(s)
Arnau Garcia-Fernandez a.garciafernandez@erasmusmc.nl, Pedro Miranda-Afonso p.mirandaafonso@erasmusmc.nl and Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
References
Antolini, L., Boracchi, P., and Biganzoli, E. (2005). A time-dependent discrimination index for survival data. Statistics in Medicine 24, 3927–3944.
Harrell, F., Kerry, L. and Mark, D. (1996). Multivariable prognostic models: issues in developing models, evaluating assumptions and adequacy, and measuring and reducing errors. Statistics in Medicine 15, 361–387.
Heagerty, P. and Zheng, Y. (2005). Survival model predictive accuracy and ROC curves. Biometrics 61, 92–105.
Rizopoulos, D. (2016). The R package JMbayes for fitting joint models for longitudinal and time-to-event data using MCMC. Journal of Statistical Software 72(7), 1–45. doi:10.18637/jss.v072.i07.
Rizopoulos, D. (2012) Joint Models for Longitudinal and Time-to-Event Data: with Applications in R. Boca Raton: Chapman and Hall/CRC.
Rizopoulos, D. (2011). Dynamic predictions and prospective accuracy in joint models for longitudinal and time-to-event data. Biometrics 67, 819–829.
Rizopoulos, D., Molenberghs, G. and Lesaffre, E.M.E.H. (2017). Dynamic predictions with time-dependent covariates in survival analysis using joint modeling and landmarking. Biometrical Journal 59, 1261–1276.
See Also
Examples
# We fit a multivariate joint model
pbc2.id$status2 <- as.numeric(pbc2.id$status != 'alive')
CoxFit <- coxph(Surv(years, status2) ~ sex, data = pbc2.id)
fm1 <- lme(log(serBilir) ~ ns(year, 3) * sex, data = pbc2,
random = ~ ns(year, 3) | id, control = lmeControl(opt = 'optim'))
fm2 <- lme(prothrombin ~ ns(year, 2) * sex, data = pbc2,
random = ~ ns(year, 2) | id, control = lmeControl(opt = 'optim'))
jointFit <- jm(CoxFit, list(fm1, fm2), time_var = "year", n_chains = 1L)
# We use landmark time 3 and prediction horizon 4.
tvAUC(jointFit, newdata = pbc2, Tstart = 3, Dt = 4, cores = 1L)
# Considering the Cox model and the IPW approach for the estimation
tvAUC(CoxFit, newdata = pbc2.id, Tstart = 6, Dt = 4, type_weights = "IPCW")
Brier Score for Dynamic Predictions under Left-Truncated and Right-Censored Data
Description
Computes estimates of the Brier score at a specified horizon time (Thoriz), using longitudinal information available up to a given starting time point (Tstart). The function supports both joint models and Cox proportional hazards models, and provides inverse probability weighting and model-based estimation methods.
Usage
tvBrier(object, newdata, Tstart, ...)
## S3 method for class 'jm'
tvBrier(object, newdata, Tstart, Thoriz = NULL, Dt = NULL,
integrated = FALSE, type_weights = c("model-based", "IPCW"),
model_weights = NULL, eventData_fun = NULL,
parallel = c("snow", "multicore"),
cores = parallelly::availableCores(omit = 1L), ...)
## S3 method for class 'coxph'
tvBrier(object, newdata, Tstart, Thoriz = NULL, Dt = NULL,
integrated = FALSE,
type_weights = c("model-based", "IPCW"), ...)
Arguments
object |
an object inheriting from class |
newdata |
a data.frame that contains the longitudinal and covariate information for the subjects for which prediction of survival probabilities is required. If a |
Tstart |
numeric scalar denoting the time point up to which longitudinal information is to be used to derive predictions. |
Thoriz |
numeric scalar denoting the time point for which a prediction of the survival status is of interest; |
Dt |
numeric scalar denoting the length of the time interval of prediction; either |
integrated |
logical; if |
type_weights |
character string denoting the type of weights to use to account for censorting. Options are model-based (default) and inverse probability weighting (using the Kaplan-Meier estimate of the censoring distribution, and adjusting for left truncation if necessary). |
model_weights |
a numeric vector of weights to combine predictions when |
eventData_fun |
a function that takes as input the |
parallel |
character string; what type of parallel computing to use. |
cores |
integer denoting the number of cores to be used when a library of joint models has been provided in
|
... |
additional arguments passed to |
Details
The integrated Brier score allows us to summarize the predictive accuracy in the interval of interest (t,t+s] by computing the integral iBS(t+s,t)=\frac{1}{s}\int^{t+s}_t BS(z,t) dz. The integral is approximated numerically via Simpson's rule.
Value
A list of class tvBrier with components:
Brier |
a numeric scalar denoting the estimated Brier score. |
nr |
a numeric scalar denoting the number of subjects at risk at time |
nint |
a numeric scalar denoting the number of subjects with an event in ( |
ncens |
a numeric scalar denoting the number of subjects with a censored time in ( |
Tstart |
a copy of the |
Thoriz |
a copy of the |
integrated |
a copy of the |
type_weights |
a copy of the |
LT_MS |
a logical that is |
classObject |
the class of |
nameObject |
the name of |
Author(s)
Arnau Garcia-Fernandez a.garciafernandez@erasmusmc.nl, Pedro Miranda-Afonso p.mirandaafonso@erasmusmc.nl and Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
References
Rizopoulos, D. (2016). The R package JMbayes for fitting joint models for longitudinal and time-to-event data using MCMC. Journal of Statistical Software 72(7), 1–45. doi:10.18637/jss.v072.i07.
Rizopoulos, D. (2012) Joint Models for Longitudinal and Time-to-Event Data: with Applications in R. Boca Raton: Chapman and Hall/CRC.
Rizopoulos, D. (2011). Dynamic predictions and prospective accuracy in joint models for longitudinal and time-to-event data. Biometrics 67, 819–829.
Rizopoulos, D., Molenberghs, G. and Lesaffre, E.M.E.H. (2017). Dynamic predictions with time-dependent covariates in survival analysis using joint modeling and landmarking. Biometrical Journal 59, 1261–1276.
See Also
Examples
# We fit a multivariate joint model
pbc2.id$status2 <- as.numeric(pbc2.id$status != 'alive')
CoxFit <- coxph(Surv(years, status2) ~ sex, data = pbc2.id)
fm1 <- lme(log(serBilir) ~ ns(year, 3) * sex, data = pbc2,
random = ~ ns(year, 3) | id, control = lmeControl(opt = 'optim'))
fm2 <- lme(prothrombin ~ ns(year, 2) * sex, data = pbc2,
random = ~ ns(year, 2) | id, control = lmeControl(opt = 'optim'))
jointFit <- jm(CoxFit, list(fm1, fm2), time_var = "year", n_chains = 1L)
# We use landmark time 3 and prediction horizon 4.
tvBrier(jointFit, newdata = pbc2, Tstart = 3, Dt = 4, cores = 1L)
# Considering the Cox model and the IPW approach for the estimation
tvBrier(CoxFit, newdata = pbc2.id, Tstart = 6, Dt = 4, type_weights = "IPCW")
Expected Cost for Dynamic Predictions under Left-Truncated and Right-Censored Data
Description
Computes estimates of the expected cost for a given decision threshold (decision_threshold) at a specified horizon time (Thoriz), using longitudinal information available up to a given starting time point (Tstart). The function supports joint models, Cox proportional hazards models and predictions obtained from any method. It provides inverse probability weighting and model-based estimation methods.
Usage
tvEC(object, ...)
## Default S3 method:
tvEC(object, Time, event, LT_Time = NULL, Tstart,
decision_threshold = NULL, Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"),
preds_MB = NULL, name_model = NULL, ...)
## S3 method for class 'jm'
tvEC(object, newdata, Tstart,
decision_threshold = NULL, Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"), name_model = NULL, ...)
## S3 method for class 'coxph'
tvEC(object, newdata, Tstart,
decision_threshold = NULL, Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"), name_model = NULL, ...)
Arguments
object |
an object inheriting from class |
newdata |
a data.frame that contains the longitudinal and covariate information for the subjects for which prediction of survival probabilities is required. If a |
Tstart |
numeric scalar denoting the time point up to which longitudinal information is to be used to derive predictions. |
decision_threshold |
numeric scalar between 0 and 1 denoting the decision threshold used in the expected cost. |
Time, event, LT_Time |
numeric vectors that must be specified when using the default method to compute the metric by directly using a vector of predictions, observed times ( |
Thoriz |
numeric scalar denoting the time point for which a prediction of the survival status is of interest; |
Dt |
numeric scalar denoting the length of the time interval of prediction; either |
type_weights |
character string denoting the type of weights to use to account for censorting. Options are model-based (default) and inverse probability weighting (using the Kaplan-Meier estimate of the censoring distribution, and adjusting for left truncation if necessary). |
preds_MB |
a numeric vector containing the model-based weights to be used for the individuals censored within ( |
name_model |
character string denoting the name of the model or object used for prediction evaluation; default is |
... |
additional arguments passed to |
Value
A list of class tvMetric with components:
metric |
a numeric scalar denoting the estimated expected cost. |
metric_type |
the character string |
nr |
a numeric scalar denoting the number of subjects at risk at time |
nint |
a numeric scalar denoting the number of subjects with an event in ( |
ncens |
a numeric scalar denoting the number of subjects with a censored time in ( |
Tstart |
a copy of the |
Thoriz |
a copy of the |
type_weights |
a copy of the |
metric_info |
a copy of the |
LT_MS |
a logical that is |
classObject |
the class of |
nameObject |
the name of the model; either a copy of the |
Author(s)
Arnau Garcia-Fernandez a.garciafernandez@erasmusmc.nl, Pedro Miranda-Afonso p.mirandaafonso@erasmusmc.nl and Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
References
Van Claster, B., et al. (2025). Evaluation of performance measures in predictive artificial intelligence models to support medical decisions: overview and guidance. The Lancet Digital Health.
See Also
decision_curves, tvIWEC, tvNB, predict, jm
Examples
# We fit a multivariate joint model
pbc2.id$status2 <- as.numeric(pbc2.id$status != 'alive')
CoxFit <- coxph(Surv(years, status2) ~ sex, data = pbc2.id)
fm1 <- lme(log(serBilir) ~ ns(year, 3) * sex, data = pbc2,
random = ~ ns(year, 3) | id, control = lmeControl(opt = 'optim'))
fm2 <- lme(prothrombin ~ ns(year, 2) * sex, data = pbc2,
random = ~ ns(year, 2) | id, control = lmeControl(opt = 'optim'))
jointFit <- jm(CoxFit, list(fm1, fm2), time_var = "year", n_chains = 1L)
# Expected cost with decision threshold 0.2, prediction horizon 8
# and landmark time 5
tvEC(jointFit, newdata = pbc2, Tstart = 5, Dt = 3, decision_threshold = 0.2,
cores = 1L)
# Considering the Cox model and IPW approach for estimation:
tvEC(CoxFit, newdata = pbc2.id, Tstart = 5, Dt = 3, decision_threshold = 0.2,
type_weights = "IPCW")
# Considering the vectors with predictions, observed times, event indicator and
# left-truncated times. We consider the time window (5,8]. We use the default method:
pbc2.id$lt <- runif(nrow(pbc2.id), 0, pbc2.id$years)
sfit0 <- summary(survfit(CoxFit, newdata = pbc2.id), times = 5)
sfit <- summary(survfit(CoxFit, newdata = pbc2.id), times = 8)
predictions <- 1.0 - (as.matrix(sfit$surv)[1L, ] / as.matrix(sfit0$surv)[1L, ])
tvEC(predictions, pbc2.id$years, pbc2.id$status2, pbc2.id$lt, Tstart = 5, Thoriz = 8,
type_weights = "IPCW", decision_threshold = 0.25)
# Now, we consider the default method, but using the model-based estimator:
ind_censoring <- pbc2.id$years > 5 & pbc2.id$lt < 5 & pbc2.id$years < 8 & pbc2.id$status2 == 0
sfit2_8 <- summary(survfit(CoxFit, newdata = pbc2.id[ind_censoring, ]),
times = 8)
sfit_cens <- summary(survfit(CoxFit, newdata = pbc2.id[ind_censoring, ]),
times = pbc2.id$years[ind_censoring])
preds_MB <- rep(NA, length(pbc2.id$years))
preds_MB[ind_censoring] <- 1.0 - (as.matrix(sfit2_8$surv)[1L, ] / as.matrix(sfit_cens$surv)[1L, ])
tvEC(predictions, Time = pbc2.id$years, event = pbc2.id$status2, LT_Time = pbc2.id$lt,
Tstart = 5, Dt = 3, type_weights = "model-based", preds_MB = preds_MB,
decision_threshold = 0.3)
Expected Predictive Cross Entropy for Dynamic Predictions under Right-Censored Data
Description
Computes estimates of the expected predictive cross entropy (EPCE) at a specified horizon time (Thoriz), using longitudinal information available up to a given starting time point (Tstart). The function supports joint models and provides the model-based estimation method.
Usage
tvEPCE(object, newdata, Tstart, Thoriz = NULL, Dt = NULL,
eps = 0.001, model_weights = NULL, eventData_fun = NULL,
parallel = c("snow", "multicore"),
cores = parallelly::availableCores(omit = 1L), ...)
Arguments
object |
an object inheriting from class |
newdata |
a data.frame that contains the longitudinal and covariate information for the subjects for which prediction of survival probabilities is required. The names of the variables in this data.frame must be the same as in the data.frames that were used to fit the linear mixed effects and the event process model that were supplied as the two first argument of |
Tstart |
numeric scalar denoting the time point up to which longitudinal information is to be used to derive predictions. |
Thoriz |
numeric scalar denoting the time point for which a prediction of the survival status is of interest; |
Dt |
numeric scalar denoting the length of the time interval of prediction; either |
eps |
numeric scalar used in the approximation of the hazard function in the expected predictive cross-entropy. |
model_weights |
a numeric vector of weights to combine predictions when |
eventData_fun |
a function that takes as input the |
parallel |
character string; what type of parallel computing to use. |
cores |
integer denoting the number of cores to be used when a library of joint models has been provided in
|
... |
additional arguments passed to |
Value
A list of class tvEPCE with components:
EPCE |
a numeric scalar denoting the estimated EPCE. |
nr |
a numeric scalar denoting the number of subjects at risk at time |
nint |
a numeric scalar denoting the number of subjects with an event in ( |
ncens |
a numeric scalar denoting the number of subjects with a censored time in ( |
Tstart |
a copy of the |
Thoriz |
a copy of the |
type_weights |
a copy of the |
classObject |
the class of |
nameObject |
the name of |
Author(s)
Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
References
Commenges, D., Liquet, B., and Proust-Lima, C. (2012). Choice of prognostic estimators in joint models by estimating differences of expected conditional Kullback-Leibler risks. Biometrics 68, 380–387.
Rizopoulos, D. (2016). The R package JMbayes for fitting joint models for longitudinal and time-to-event data using MCMC. Journal of Statistical Software 72(7), 1–45. doi:10.18637/jss.v072.i07.
Rizopoulos, D. (2012) Joint Models for Longitudinal and Time-to-Event Data: with Applications in R. Boca Raton: Chapman and Hall/CRC.
Rizopoulos, D. (2011). Dynamic predictions and prospective accuracy in joint models for longitudinal and time-to-event data. Biometrics 67, 819–829.
Rizopoulos, D., Molenberghs, G. and Lesaffre, E.M.E.H. (2017). Dynamic predictions with time-dependent covariates in survival analysis using joint modeling and landmarking. Biometrical Journal 59, 1261–1276.
See Also
Examples
# We fit a multivariate joint model
pbc2.id$status2 <- as.numeric(pbc2.id$status != 'alive')
CoxFit <- coxph(Surv(years, status2) ~ sex, data = pbc2.id)
fm1 <- lme(log(serBilir) ~ ns(year, 3) * sex, data = pbc2,
random = ~ ns(year, 3) | id, control = lmeControl(opt = 'optim'))
fm2 <- lme(prothrombin ~ ns(year, 2) * sex, data = pbc2,
random = ~ ns(year, 2) | id, control = lmeControl(opt = 'optim'))
jointFit <- jm(CoxFit, list(fm1, fm2), time_var = "year", n_chains = 1L)
# We use landmark time 3 and prediction horizon 4.
tvEPCE(jointFit, newdata = pbc2, Tstart = 3, Dt = 4, cores = 1L)
Integrated Weighted Expected Cost for Dynamic Predictions under Left-Truncated and Right-Censored Data
Description
Computes estimates of the integrated weighted expected cost (IWEC) for a given weight function within the beta family at a specified horizon time (Thoriz), using longitudinal information available up to a given starting time point (Tstart). The function supports joint models, Cox proportional hazards models and predictions obtained from any method. It provides inverse probability weighting and model-based estimation methods.
Usage
tvIWEC(object, ...)
## Default S3 method:
tvIWEC(object, Time, event, LT_Time = NULL, Tstart,
shape1 = NULL, shape2 = NULL, mod = NULL, interv = NULL,
mass = 0.95, Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"), preds_MB = NULL,
opt_interv = c(1, 500), name_model = NULL, ...)
## S3 method for class 'jm'
tvIWEC(object, newdata, Tstart,
shape1 = NULL, shape2 = NULL, mod = NULL, interv = NULL, mass = 0.95,
Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"),
opt_interv = c(1, 500), name_model = NULL, ...)
## S3 method for class 'coxph'
tvIWEC(object, newdata, Tstart,
shape1 = NULL, shape2 = NULL, mod = NULL, interv = NULL, mass = 0.95,
Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"),
opt_interv = c(1, 500), name_model = NULL, ...)
Arguments
object |
an object inheriting from class |
newdata |
a data.frame that contains the longitudinal and covariate information for the subjects for which prediction of survival probabilities is required. If a |
Tstart |
numeric scalar denoting the time point up to which longitudinal information is to be used to derive predictions. |
Time, event, LT_Time |
numeric vectors that must be specified when using the default method to compute the metric by directly using a vector of predictions, observed times ( |
shape1, shape2 |
numeric scalars greater or equal to 0 denoting the shape parameteres for the beta family of weight functions (see below for details). |
mod, mass, interv |
two numeric scalars between 0 and 1 and a numeric vector with two scalars between 0 and 1, denoting the mode of the weight function and the mass (default is 95%) to be allocated within the interval defined by the two values in the numeric vector. These arguments can be used to compute the shape parameters. See below for details. |
Thoriz |
numeric scalar denoting the time point for which a prediction of the survival status is of interest; |
Dt |
numeric scalar denoting the length of the time interval of prediction; either |
type_weights |
character string denoting the type of weights to use to account for censorting. Options are model-based (default) and inverse probability weighting (using the Kaplan-Meier estimate of the censoring distribution, and adjusting for left truncation if necessary). |
preds_MB |
a numeric vector containing the model-based weights to be used for the individuals censored within ( |
opt_interv |
a numeric vector containing the end-points of the interval to be searched for the root. This argumentis used when |
name_model |
character string denoting the name of the model or object used for prediction evaluation; default is |
... |
additional arguments passed to |
Details
The IWEC is implemented using the beta family of weight functions, which is defined by the two-parameter form w(c;\text{shape1}, \text{shape2})=c^{\text{shape1}-1}(1-c)^{\text{shape2}-1}/B(\text{shape1}, \text{shape2}), where \text{shape1}, \text{shape2}\geq 0 are shape parameters and B(\text{shape1},\text{shape2})=1 if \text{shape1}=\text{shape2}=0, and otherwise denotes the beta function.
When mod, mass and interv are provided we compute the shape parameters shape1 and shape2 by solving the system consisting of the two equations: \text{mod}=\frac{\text{shape1} - 1}{\text{shape1} + \text{shape2} - 2} and \text{Pr}(X \in \text{interv}) = \text{mass}, where X follows a beta distribution with shape parameters shape1 and shape2. To solve this system, the uniroot() function is internally used. The user can change the interval argument of the uniroot() function using the opt_interv argument.
Value
A list of class tvMetric with components:
metric |
a numeric scalar denoting the estimated IWEC. |
metric_type |
the character string |
nr |
a numeric scalar denoting the number of subjects at risk at time |
nint |
a numeric scalar denoting the number of subjects with an event in ( |
ncens |
a numeric scalar denoting the number of subjects with a censored time in ( |
Tstart |
a copy of the |
Thoriz |
a copy of the |
type_weights |
a copy of the |
metric_info |
a copy of |
LT_MS |
a logical that is |
classObject |
the class of |
nameObject |
the name of the model; either a copy of the |
Author(s)
Arnau Garcia-Fernandez a.garciafernandez@erasmusmc.nl, Pedro Miranda-Afonso p.mirandaafonso@erasmusmc.nl and Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
See Also
decision_curves, tvNB, tvEC,predict, jm
Examples
# We fit a multivariate joint model
pbc2.id$status2 <- as.numeric(pbc2.id$status != 'alive')
CoxFit <- coxph(Surv(years, status2) ~ sex, data = pbc2.id)
fm1 <- lme(log(serBilir) ~ ns(year, 3) * sex, data = pbc2,
random = ~ ns(year, 3) | id, control = lmeControl(opt = 'optim'))
fm2 <- lme(prothrombin ~ ns(year, 2) * sex, data = pbc2,
random = ~ ns(year, 2) | id, control = lmeControl(opt = 'optim'))
jointFit <- jm(CoxFit, list(fm1, fm2), time_var = "year", n_chains = 1L)
# IWEC with a weight function in which relevant decision thresholds are (0.1, 0.3),
# the mode is 0.2 and the mass within the interval is 80 percent.
# We use landmark time 6 and prediction horizon 4.
tvIWEC(jointFit, newdata = pbc2, Tstart = 6, Dt = 4, mod = 0.2,
interv = c(0.1, 0.3), mass = 0.8, cores = 1L)
# Considering the Cox model, the IPW approach for estimation and
# shape parameters 12 and 38
tvIWEC(CoxFit, newdata = pbc2.id, Tstart = 6, Dt = 4, shape1 = 12, shape2 = 38,
type_weights = "IPCW")
# Considering the vectors with predictions, observed times, event indicator and
# left-truncated times. We use the default method:
pbc2$lt <- unlist(by(pbc2, pbc2$id, function(x) rep(runif(1, 0, x$years), nrow(x))))
pbc2.id$lt <- runif(nrow(pbc2.id), 0, pbc2.id$years)
sfit0 <- summary(survfit(CoxFit, newdata = pbc2.id), times = 5)
sfit <- summary(survfit(CoxFit, newdata = pbc2.id), times = 5 + 3)
predictions <- 1.0 - (as.matrix(sfit$surv)[1L, ] / as.matrix(sfit0$surv)[1L, ])
tvIWEC(predictions, pbc2.id$years, pbc2.id$status2, pbc2.id$lt, Tstart = 5, Dt = 3,
type_weights = "IPCW", shape1 = 12, shape2 = 35)
# Now, we consider the default method, but using the model-based estimator:
ind_censoring <- pbc2.id$years > 5 & pbc2.id$lt < 5 & pbc2.id$years < 8 & pbc2.id$status2 == 0
sfit2_8 <- summary(survfit(CoxFit, newdata = pbc2.id[ind_censoring, ]),
times = 8)
sfit_cens <- summary(survfit(CoxFit, newdata = pbc2.id[ind_censoring, ]),
times = pbc2.id$years[ind_censoring])
preds_MB <- rep(NA, length(pbc2.id$years))
preds_MB[ind_censoring] <- 1.0 - (as.matrix(sfit2_8$surv)[1L, ] / as.matrix(sfit_cens$surv)[1L, ])
tvIWEC(predictions, Time = pbc2.id$years, event = pbc2.id$status2, LT_Time = pbc2.id$lt,
Tstart = 5, Dt = 3, type_weights = "model-based", preds_MB = preds_MB,
mod = 0.33, interv = c(0.125, 0.46), mass = 0.7)
Net Benefit for Dynamic Predictions under Left-Truncated and Right-Censored Data
Description
Computes estimates of the net benefit for a given decision threshold (decision_threshold) at a specified horizon time (Thoriz), using longitudinal information available up to a given starting time point (Tstart). The function supports joint models, Cox proportional hazards models and predictions obtained from any method. It provides inverse probability weighting and model-based estimation methods.
Usage
tvNB(object, ...)
## Default S3 method:
tvNB(object, Time, event, LT_Time = NULL, Tstart,
decision_threshold = NULL, Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"),
preds_MB = NULL, name_model = NULL, ...)
## S3 method for class 'jm'
tvNB(object, newdata, Tstart,
decision_threshold = NULL, Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"), name_model = NULL, ...)
## S3 method for class 'coxph'
tvNB(object, newdata, Tstart,
decision_threshold = NULL, Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"), name_model = NULL, ...)
Arguments
object |
an object inheriting from class |
newdata |
a data.frame that contains the longitudinal and covariate information for the subjects for which prediction of survival probabilities is required. If a |
Tstart |
numeric scalar denoting the time point up to which longitudinal information is to be used to derive predictions. |
decision_threshold |
numeric scalar between 0 and 1 denoting the decision threshold used in the net benefit. |
Time, event, LT_Time |
numeric vectors that must be specified when using the default method to compute the metric by directly using a vector of predictions, observed times ( |
Thoriz |
numeric scalar denoting the time point for which a prediction of the survival status is of interest; |
Dt |
numeric scalar denoting the length of the time interval of prediction; either |
type_weights |
character string denoting the type of weights to use to account for censorting. Options are model-based (default) and inverse probability weighting (using the Kaplan-Meier estimate of the censoring distribution, and adjusting for left truncation if necessary). |
preds_MB |
a numeric vector containing the model-based weights to be used for the individuals censored within ( |
name_model |
character string denoting the name of the model or object used for prediction evaluation; default is |
... |
additional arguments passed to |
Value
A list of class tvMetric with components:
metric |
a numeric scalar denoting the estimated net benefit. |
metric_type |
the character string |
nr |
a numeric scalar denoting the number of subjects at risk at time |
nint |
a numeric scalar denoting the number of subjects with an event in ( |
ncens |
a numeric scalar denoting the number of subjects with a censored time in ( |
Tstart |
a copy of the |
Thoriz |
a copy of the |
type_weights |
a copy of the |
metric_info |
a copy of the |
LT_MS |
a logical that is |
classObject |
the class of |
nameObject |
the name of the model; either a copy of the |
Author(s)
Arnau Garcia-Fernandez a.garciafernandez@erasmusmc.nl, Pedro Miranda-Afonso p.mirandaafonso@erasmusmc.nl and Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
References
Vickers, Andrew J and Elkin, Elena B (2006). Decision curve analysis: a novel method for evaluating prediction models. Medical Decision Making 26, 565–574.
See Also
decision_curves, tvIWEC, tvEC, predict, jm
Examples
# We fit a multivariate joint model
pbc2.id$status2 <- as.numeric(pbc2.id$status != 'alive')
CoxFit <- coxph(Surv(years, status2) ~ sex, data = pbc2.id)
fm1 <- lme(log(serBilir) ~ ns(year, 3) * sex, data = pbc2,
random = ~ ns(year, 3) | id, control = lmeControl(opt = 'optim'))
fm2 <- lme(prothrombin ~ ns(year, 2) * sex, data = pbc2,
random = ~ ns(year, 2) | id, control = lmeControl(opt = 'optim'))
jointFit <- jm(CoxFit, list(fm1, fm2), time_var = "year", n_chains = 1L)
# Net benefit with decision threshold 0.3, prediction horizon 7
# and landmark time 4
tvNB(jointFit, newdata = pbc2, Tstart = 4, Dt = 3, decision_threshold = 0.3,
cores = 1L)
# Considering the Cox model and IPW approach for estimation:
tvNB(CoxFit, newdata = pbc2.id, Tstart = 4, Dt = 3, decision_threshold = 0.3,
type_weights = "IPCW")
# Considering the vectors with predictions, observed times, event indicator and
# left-truncated times. We use the default method:
pbc2.id$lt <- runif(nrow(pbc2.id), 0, pbc2.id$years)
sfit0 <- summary(survfit(CoxFit, newdata = pbc2.id), times = 5)
sfit <- summary(survfit(CoxFit, newdata = pbc2.id), times = 5 + 3)
predictions <- 1.0 - (as.matrix(sfit$surv)[1L, ] / as.matrix(sfit0$surv)[1L, ])
tvNB(predictions, pbc2.id$years, pbc2.id$status2, pbc2.id$lt, Tstart = 5, Thoriz = 8,
type_weights = "IPCW", decision_threshold = 0.25)
# Now, we consider the default method, but using the model-based estimator:
ind_censoring <- pbc2.id$years > 5 & pbc2.id$lt < 5 & pbc2.id$years < 8 & pbc2.id$status2 == 0
sfit2_8 <- summary(survfit(CoxFit, newdata = pbc2.id[ind_censoring, ]),
times = 8)
sfit_cens <- summary(survfit(CoxFit, newdata = pbc2.id[ind_censoring, ]),
times = pbc2.id$years[ind_censoring])
preds_MB <- rep(NA, length(pbc2.id$years))
preds_MB[ind_censoring] <- 1.0 - (as.matrix(sfit2_8$surv)[1L, ] / as.matrix(sfit_cens$surv)[1L, ])
tvNB(predictions, Time = pbc2.id$years, event = pbc2.id$status2, LT_Time = pbc2.id$lt,
Tstart = 5, Dt = 3, type_weights = "model-based", preds_MB = preds_MB,
decision_threshold = 0.3)
Receiver Operating Characteristic Curve (ROC) for Dynamic Predictions under Left-Truncated and Right-Censored Data
Description
Computes estimates of the ROC curve at a specified horizon time (Thoriz), using longitudinal information available up to a given starting time point (Tstart). The function supports both joint models and Cox proportional hazards models, and provides inverse probability weighting and model-based estimation methods.
Usage
tvROC(object, newdata, Tstart, ...)
## S3 method for class 'jm'
tvROC(object, newdata, Tstart, Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"), ...)
## S3 method for class 'coxph'
tvROC(object, newdata, Tstart, Thoriz = NULL, Dt = NULL,
type_weights = c("model-based", "IPCW"), ...)
Arguments
object |
an object inheriting from class |
newdata |
a data.frame that contains the longitudinal and covariate information for the subjects for which prediction of survival probabilities is required. If a |
Tstart |
numeric scalar denoting the time point up to which longitudinal information is to be used to derive predictions. |
Thoriz |
numeric scalar denoting the time point for which a prediction of the survival status is of interest; |
Dt |
numeric scalar denoting the length of the time interval of prediction; either |
type_weights |
character string denoting the type of weights to use to account for censorting. Options are model-based (default) and inverse probability weighting (using the Kaplan-Meier estimate of the censoring distribution, and adjusting for left truncation if necessary). |
... |
additional arguments passed to |
Value
A list of class tvROC with components:
TP, FP, nTP, nFN, nTN, qSN, qSP, qOverall |
accuracy indexes. |
F1score, Youden |
numeric scalars with the optimal cut-point using the F1 score and the Youden index. |
thr |
numeric vector of thresholds. |
Tstart |
a copy of the |
Thoriz |
a copy of the |
nr |
a numeric scalar denoting the number of subjects at risk at time |
classObject |
the class of |
type_weights |
a copy of the |
LT_MS |
a logical that is |
nameObject |
the name of |
Author(s)
Arnau Garcia-Fernandez a.garciafernandez@erasmusmc.nl, Pedro Miranda-Afonso p.mirandaafonso@erasmusmc.nl and Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
References
Antolini, L., Boracchi, P., and Biganzoli, E. (2005). A time-dependent discrimination index for survival data. Statistics in Medicine 24, 3927–3944.
Harrell, F., Kerry, L. and Mark, D. (1996). Multivariable prognostic models: issues in developing models, evaluating assumptions and adequacy, and measuring and reducing errors. Statistics in Medicine 15, 361–387.
Heagerty, P. and Zheng, Y. (2005). Survival model predictive accuracy and ROC curves. Biometrics 61, 92–105.
Rizopoulos, D. (2016). The R package JMbayes for fitting joint models for longitudinal and time-to-event data using MCMC. Journal of Statistical Software 72(7), 1–45. doi:10.18637/jss.v072.i07.
Rizopoulos, D. (2012) Joint Models for Longitudinal and Time-to-Event Data: with Applications in R. Boca Raton: Chapman and Hall/CRC.
Rizopoulos, D. (2011). Dynamic predictions and prospective accuracy in joint models for longitudinal and time-to-event data. Biometrics 67, 819–829.
Rizopoulos, D., Molenberghs, G. and Lesaffre, E.M.E.H. (2017). Dynamic predictions with time-dependent covariates in survival analysis using joint modeling and landmarking. Biometrical Journal 59, 1261–1276.
See Also
Examples
# We fit a multivariate joint model
pbc2.id$status2 <- as.numeric(pbc2.id$status != 'alive')
CoxFit <- coxph(Surv(years, status2) ~ sex, data = pbc2.id)
fm1 <- lme(log(serBilir) ~ ns(year, 3) * sex, data = pbc2,
random = ~ ns(year, 3) | id, control = lmeControl(opt = 'optim'))
fm2 <- lme(prothrombin ~ ns(year, 2) * sex, data = pbc2,
random = ~ ns(year, 2) | id, control = lmeControl(opt = 'optim'))
jointFit <- jm(CoxFit, list(fm1, fm2), time_var = "year", n_chains = 1L)
# We use landmark time 4 and prediction horizon 3.
roc <- tvROC(jointFit, newdata = pbc2, Tstart = 4, Dt = 3, cores = 1L)
roc
# We plot the ROC curve
plot(roc, legend = TRUE, optimal_cutoff = "Youden")
Variogram for Longitudinal Data
Description
It computes the semi-variogram for longitudinal data.
Usage
variogram(y, times, id)
Arguments
y |
a numeric vector of longitudinal responses. |
times |
a numeric vector of times at which the longitudinal responses were collected. |
id |
a numeric vector of a factor of subject id numbers. |
Value
A list with two components, i.e., svar, a two-column matrix with the time lags and the variogram
values, and sigma2 the total variance.
Author(s)
Dimitris Rizopoulos d.rizopoulos@erasmusmc.nl
Examples
ind <- aids$patient == 2
yy <- aids$CD4[ind]
tt <- aids$obstime[ind]
ids <- aids$patient[ind]
variogram(yy, tt, ids)