### Plot Predicted Risks Example Setup Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Example setup for plotting predicted risks, requiring the 'prodlim' package. ```R library(prodlim) ``` -------------------------------- ### Install riskRegression from GitHub Source: https://cran.r-project.org/web/packages/riskRegression/readme/README.html Use the devtools package to install the latest version of riskRegression from the specified GitHub repository. ```R library(devtools) install_github("tagteam/riskRegression") ``` -------------------------------- ### Execute wglm examples Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Examples demonstrating the use of wglm with simulated data under various scenarios including no censoring, right-censoring, and competing risks. ```R library(survival) #### simulate data #### set.seed(10) n <- 250 tau <- 1:5 d <- sampleData(n, outcome = "competing.risks") dFull <- d[event!=0] ## (artificially) remove censoring dSurv <- d[event!=2] ## (artificially) remove competing risk #### no censoring #### e.wglm <- wglm(Surv(time,event) ~ X1, times = tau, data = dFull, product.limit = TRUE) e.wglm ## same as a logistic regression at each timepoint coef(e.wglm) confint(e.wglm) model.tables(e.wglm) summary(ate(e.wglm, data = dFull, times = tau, treatment = "X1", verbose = FALSE)) #### right-censoring #### ## no covariante in the censoring model (independent censoring) eC.wglm <- wglm(Surv(time,event) ~ X1, times = tau, data = dSurv, product.limit = TRUE) summary(eC.wglm) weights(eC.wglm) ## with covariates in the censoring model eC2.wglm <- wglm(Surv(time,event) ~ X1 + X8, formula.censor = ~ X1*X8, times = tau, data = dSurv) eC2.wglm #### Competing risks #### ## here Kaplan-Meier as censoring model eCR.wglm <- wglm(Surv(time,event) ~ X1, formula.censor = ~X1, times = tau, data = d) eCR.wglm summary(eCR.wglm) eCR.wglm <- wglm(Surv(time,event) ~ X1, formula.censor = ~X1, times = tau, data = d) ``` -------------------------------- ### Ctree Wrapper Function Example Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Example usage of the Ctree wrapper function, which adds the call to a ctree object. Requires the 'party' and 'survival' packages. ```r if (require("party",quietly=TRUE)){ library(prodlim) library(party) library(survival) set.seed(50) d <- SimSurv(50) nd <- data.frame(X1=c(0,1,0),X2=c(-1,0,1)) f <- Ctree(Surv(time,status)~X1+X2,data=d) predictRisk(f,newdata=nd,times=c(3,8)) } ``` -------------------------------- ### Synthesize Data Example Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Demonstrates fitting a model to pbc data and simulating new data to compare hazard ratios. ```R # pbc data library(survival) library(lava) data(pbc) pbc <- na.omit(pbc[,c("time","status","sex","age","bili")]) pbc$logbili <- log(pbc$bili) v_synt <- synthesize(object=Hist(time,status)~logbili+age+sex,data=pbc) set.seed(8) d <- simsynth(v_synt,38) fit_sim <- coxph(Surv(time,status==1)~age+sex+logbili,data=d) fit_real <- coxph(Surv(time,status==1)~age+sex+logbili,data=pbc) # compare estimated log-hazard ratios between simulated and real data cbind(coef(fit_sim),coef(fit_real)) ``` -------------------------------- ### Check package versions Source: https://cran.r-project.org/web/packages/riskRegression/vignettes/IPA.html Displays the installed versions of required packages for the riskRegression workflow. ```R data.table:[1] ‘1.17.8’ survival:[1] ‘3.8.3’ riskRegression:[1] ‘2025.9.5’ Publish:[1] ‘2025.7.24’ ``` -------------------------------- ### Predicting Risks with Various Models Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Examples demonstrating how to use predictRisk for binary, survival, and competing risk models. ```R ## binary outcome library(rms) set.seed(7) d <- sampleData(80,outcome="binary") nd <- sampleData(80,outcome="binary") fit <- lrm(Y~X1+X8,data=d) predictRisk(fit,newdata=nd) ## survival outcome # generate survival data library(prodlim) set.seed(100) d <- sampleData(100,outcome="survival") d[,X1:=as.numeric(as.character(X1))] d[,X2:=as.numeric(as.character(X2))] # then fit a Cox model library(rms) cphmodel <- cph(Surv(time,event)~X1+X2,data=d,surv=TRUE,x=TRUE,y=TRUE) # or via survival library(survival) coxphmodel <- coxph(Surv(time,event)~X1+X2,data=d,x=TRUE,y=TRUE) # Extract predicted survival probabilities # at selected time-points: ttt <- quantile(d$time) # for selected predictor values: ndat <- data.frame(X1=c(0.25,0.25,-0.05,0.05),X2=c(0,1,0,1)) # as follows predictRisk(cphmodel,newdata=ndat,times=ttt) predictRisk(coxphmodel,newdata=ndat,times=ttt) ## simulate learning and validation data set.seed(10) learndat <- sampleData(80,outcome="survival") valdat <- sampleData(10,outcome="survival") ## use the learning data to fit a Cox model library(survival) fitCox <- coxph(Surv(time,event)~X6+X2,data=learndat,x=TRUE,y=TRUE) ## suppose we want to predict the survival probabilities for all subjects ## in the validation data at the following time points: ## 0, 1, 2, 3, 4 psurv <- predictRisk(fitCox,newdata=valdat,times=seq(0,4,1)) ## This is a matrix with event probabilities (1-survival) ## one column for each of the 5 time points ## one row for each validation set individual ## competing risks library(survival) library(riskRegression) library(prodlim) set.seed(8) train <- sampleData(80) test <- sampleData(10) cox.fit <- CSC(Hist(time,event)~X1+X6,data=train,cause=1) predictRisk(cox.fit,newdata=test,times=seq(1:10),cause=1) ## with strata cox.fit2 <- CSC(list(Hist(time,event)~strata(X1)+X6, Hist(time,cause)~X1+X6),data=train) predictRisk(cox.fit2,newdata=test,times=seq(1:10),cause=1) ``` -------------------------------- ### Load Melanoma Dataset Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Loads the Melanoma dataset. No specific setup is required beyond this command. ```r data(Melanoma) ``` -------------------------------- ### Predicting Survival with Cox Regression Models Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html This example demonstrates data preparation, Kaplan-Meier estimation, stratified models, and Cox regression predictions including handling of ties and left truncation. ```R library(survival) library(data.table) ####################### #### generate data #### ####################### set.seed(10) d <- sampleData(50,outcome="survival") ## training dataset nd <- sampleData(5,outcome="survival") ## validation dataset ## add ties d$time.round <- round(d$time,1) any(duplicated(d$time.round)) ## add categorical variables d$U <- sample(letters[1:3],replace=TRUE,size=NROW(d)) d$V <- sample(letters[5:8],replace=TRUE,size=NROW(d)) nd <- cbind(nd,d[sample(NROW(d),replace=TRUE,size=NROW(nd)),c("U","V")]) ###################### #### Kaplan Meier #### ###################### #### no ties fit.KM <- coxph(Surv(time,event)~ 1, data=d, x = TRUE, y = TRUE) predictCox(fit.KM) ## exponential approximation ePL.KM <- predictCox(fit.KM, product.limit = TRUE) ## product-limit as.data.table(ePL.KM) range(survfit(Surv(time,event)~1, data = d)$surv - ePL.KM$survival) ## same #### with ties (exponential approximation, Efron estimator for the baseline hazard) fit.KM.ties <- coxph(Surv(time.round,event)~ 1, data=d, x = TRUE, y = TRUE) predictCox(fit.KM) ## retrieving survfit results with ties fit.KM.ties <- coxph(Surv(time.round,event)~ 1, data=d, x = TRUE, y = TRUE, ties = "breslow") ePL.KM.ties <- predictCox(fit.KM, product.limit = TRUE) range(survfit(Surv(time,event)~1, data = d)$surv - ePL.KM.ties$survival) ## same ################################# #### Stratified Kaplan Meier #### ################################# fit.SKM <- coxph(Surv(time,event)~strata(X2), data=d, x = TRUE, y = TRUE) ePL.SKM <- predictCox(fit.SKM, product.limit = TRUE) ePL.SKM range(survfit(Surv(time,event)~X2, data = d)$surv - ePL.SKM$survival) ## same ################### #### Cox model #### ################### fit.Cox <- coxph(Surv(time,event)~X1 + X2 + X6, data=d, x = TRUE, y = TRUE) #### compute the baseline cumulative hazard Cox.haz0 <- predictCox(fit.Cox) Cox.haz0 range(survival::basehaz(fit.Cox)$hazard-Cox.haz0$cumhazard) ## same #### compute individual specific cumulative hazard and survival probabilities ## exponential approximation fit.predCox <- predictCox(fit.Cox, newdata=nd, times=c(3,8), se = TRUE, band = TRUE) fit.predCox ## product-limit fitPL.predCox <- predictCox(fit.Cox, newdata=nd, times=c(3,8), product.limit = TRUE, se = TRUE) fitPL.predCox ## Note: product limit vs. exponential does not affect uncertainty quantification range(fitPL.predCox$cumhazard.se - fit.predCox$cumhazard.se) ## same range(fitPL.predCox$survival.se - fit.predCox$survival.se) ## different ## except through a multiplicative factor (multiply by survival in the delta method) fitPL.predCox$survival.se - fitPL.predCox$cumhazard.se * fitPL.predCox$survival #### left truncation test2 <- list(start=c(1,2,5,2,1,7,3,4,8,8), stop=c(2,3,6,7,8,9,9,9,14,17), event=c(1,1,1,1,1,1,1,0,0,0), x=c(1,0,0,1,0,1,1,1,0,0)) m.cph <- coxph(Surv(start, stop, event) ~ 1, test2, x = TRUE) as.data.table(predictCox(m.cph)) basehaz(m.cph) ############################## #### Stratified Cox model #### ############################## #### one strata variable fit.SCox <- coxph(Surv(time,event)~X1+strata(X2)+X6, data=d, x = TRUE, y = TRUE) predictCox(fit.SCox, newdata=nd, times = c(3,12)) predictCox(fit.SCox, newdata=nd, times = c(3,12), product.limit = TRUE) ``` -------------------------------- ### Visualize Model Calibration Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Examples demonstrating calibration plotting for binary, survival, and competing risk models using the Score function output. ```R library(prodlim) # binary set.seed(10) db=sampleData(100,outcome="binary") fb1=glm(Y~X1+X5+X7,data=db,family="binomial") fb2=glm(Y~X1+X3+X6+X7,data=db,family="binomial") xb=Score(list(model1=fb1,model2=fb2),Y~1,data=db, plots="cal") plotCalibration(xb,brier.in.legend=TRUE) plotCalibration(xb,bars=TRUE,models="model1") plotCalibration(xb,models=1,bars=TRUE,names.cex=1.3) # survival library(survival) library(prodlim) dslearn=sampleData(56,outcome="survival") dstest=sampleData(100,outcome="survival") fs1=coxph(Surv(time,event)~X1+X5+X7,data=dslearn,x=1) fs2=coxph(Surv(time,event)~strata(X1)+X3+X6+X7,data=dslearn,x=1) xs=Score(list(Cox1=fs1,Cox2=fs2),Surv(time,event)~1,data=dstest, plots="cal",metrics=NULL) plotCalibration(xs) plotCalibration(xs,cens.method="local",pseudo=1) plotCalibration(xs,method="quantile") # competing risks ## Not run: data(Melanoma) f1 <- CSC(Hist(time,status)~age+sex+epicel+ulcer,data=Melanoma) f2 <- CSC(Hist(time,status)~age+sex+logthick+epicel+ulcer,data=Melanoma) x <- Score(list(model1=f1,model2=f2),Hist(time,status)~1,data=Melanoma, cause= 2,times=5*365.25,plots="cal") plotCalibration(x) ## End(Not run) ``` -------------------------------- ### predictCox Function Examples Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Examples demonstrating the usage of the predictCox function for Cox models, including baseline hazard and survival predictions. ```APIDOC ## predictCox Function Examples This section provides examples of using the `predictCox` function with Cox models, demonstrating predictions for baseline hazard, survival, and linear predictors, including stratified models and models with splines. ### Cox model examples ```R library(survival) library(ggplot2) #### simulate data #### set.seed(10) d <- sampleData(1e2, outcome = "survival") seqTau <- c(0,sort(unique(d$time[d$event==1])), max(d$time)) #### Cox model #### m.cox <- coxph(Surv(time,event)~ X1 + X2 + X3, data = d, x = TRUE, y = TRUE) ## display baseline hazard e.basehaz <- predictCox(m.cox) autoplot(e.basehaz, type = "cumhazard") ## Not run: autoplot(e.basehaz, type = "cumhazard", size.point = 0) ## without points autoplot(e.basehaz, type = "cumhazard", smooth = TRUE) autoplot(e.basehaz, type = "cumhazard", smooth = TRUE, first.derivative = TRUE) ## End(Not run) ## display baseline hazard with type of event ## Not run: e.basehaz <- predictCox(m.cox, keep.newdata = TRUE) autoplot(e.basehaz, type = "cumhazard") autoplot(e.basehaz, type = "cumhazard", shape.point = c(3,NA)) ## End(Not run) ## display predicted survival ## Not run: pred.cox <- predictCox(m.cox, newdata = d[1:2,], times = seqTau, type = "survival", keep.newdata = TRUE) autoplot(pred.cox) autoplot(pred.cox, smooth = TRUE) autoplot(pred.cox, group.by = "covariates") autoplot(pred.cox, group.by = "covariates", reduce.data = TRUE) autoplot(pred.cox, group.by = "X1", reduce.data = TRUE) ## End(Not run) ## predictions with confidence interval/bands ## Not run: pred.cox <- predictCox(m.cox, newdata = d[1:2,,drop=FALSE], times = seqTau, type = "survival", band = TRUE, se = TRUE, keep.newdata = TRUE) res <- autoplot(pred.cox, ci = TRUE, band = TRUE, plot = FALSE) res$plot + facet_wrap(~row) res2 <- autoplot(pred.cox, ci = TRUE, band = TRUE, alpha = 0.1, plot = FALSE) res2$plot + facet_wrap(~row) ## End(Not run) #### Stratified Cox model #### ## Not run: m.cox.strata <- coxph(Surv(time,event)~ strata(X1) + strata(X2) + X3 + X4, data = d, x = TRUE, y = TRUE) ## baseline hazard pred.baseline <- predictCox(m.cox.strata, keep.newdata = TRUE, type = "survival") res <- autoplot(pred.baseline) res$plot + facet_wrap(~strata, labeller = label_both) ## predictions pred.cox.strata <- predictCox(m.cox.strata, newdata = d[1:3,,drop=FALSE], time = seqTau, keep.newdata = TRUE, se = TRUE) res2 <- autoplot(pred.cox.strata, type = "survival", group.by = "strata", plot = FALSE) res2$plot + facet_wrap(~strata, labeller = label_both) + theme(legend.position="bottom") ## smooth version autoplot(pred.cox.strata, type = "survival", group.by = "strata", smooth = TRUE, ci = FALSE) ## End(Not run) #### Cox model with splines #### ## Not run: require(splines) m.cox.spline <- coxph(Surv(time,event)~ X1 + X2 + ns(X6,4), data = d, x = TRUE, y = TRUE) grid <- data.frame(X1 = factor(0,0:1), X2 = factor(0,0:1), X6 = seq(min(d$X6),max(d$X6), length.out = 100)) pred.spline <- predictCox(m.cox.spline, newdata = grid, keep.newdata = TRUE, se = TRUE, band = TRUE, centered = TRUE, type = "lp") autoplot(pred.spline, group.by = "X6") autoplot(pred.spline, group.by = "X6", alpha = 0.5) grid2 <- data.frame(X1 = factor(1,0:1), X2 = factor(0,0:1), X6 = seq(min(d$X6),max(d$X6), length.out = 100)) pred.spline <- predictCox(m.cox.spline, newdata = rbind(grid,grid2), keep.newdata = TRUE, se = TRUE, band = TRUE, centered = TRUE, type = "lp") autoplot(pred.spline, group.by = c("X6","X1"), alpha = 0.5, plot = FALSE)$plot + facet_wrap(~X1) ## End(Not run) ``` ``` -------------------------------- ### Get Data Split Method Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Specifies the algorithm for data splitting, supporting various bootstrap and cross-validation methods. Use for setting up data partitioning for model evaluation. ```R getSplitMethod(split.method, B, N, M, seed) ``` ```R # 3-fold crossvalidation getSplitMethod("cv3",B=4,N=37) # bootstrap with replacement getSplitMethod("loob",B=4,N=37) # bootstrap without replacement getSplitMethod("loob",B=4,N=37,M=20) ``` -------------------------------- ### FGR Examples for Competing Risks Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Examples demonstrating the usage of the FGR function for fitting competing risks models, including various covariate specifications and time-dependent effects. ```APIDOC ## FGR Examples for Competing Risks This section provides examples of using the `FGR` function for competing risks regression. It showcases different ways to specify covariates, including time-dependent effects using `cov2` and `tf` arguments, and demonstrates how to pass additional arguments to the underlying `crr` function. ### Examples ```R library(prodlim) library(survival) library(cmprsk) library(lava) d <- prodlim::SimCompRisk(100) f1 <- FGR(Hist(time,cause)~X1+X2,data=d) print(f1) ## crr allows that some covariates are multiplied by ## a function of time (see argument tf of crr) ## by FGR uses the identity matrix f2 <- FGR(Hist(time,cause)~cov2(X1)+X2,data=d) print(f2) ## same thing, but more explicit: f3 <- FGR(Hist(time,cause)~cov2(X1)+cov1(X2),data=d) print(f3) ## both variables can enter cov2: f4 <- FGR(Hist(time,cause)~cov2(X1)+cov2(X2),data=d) print(f4) ## change the function of time qFun <- function(x){x^2} noFun <- function(x){x} sqFun <- function(x){x^0.5} ## multiply X1 by time^2 and X2 by time: f5 <- FGR(Hist(time,cause)~cov2(X1,tf=qFun)+cov2(X2),data=d) print(f5) print(f5$crrFit) ## same results as crr with(d,crr(ftime=time, fstatus=cause, cov2=d[,c("X1","X2")], tf=function(time){cbind(qFun(time),time)})) ## still same result, but more explicit f5a <- FGR(Hist(time,cause)~cov2(X1,tf=qFun)+cov2(X2,tf=noFun),data=d) f5a$crrFit ## multiply X1 by time^2 and X2 by sqrt(time) f5b <- FGR(Hist(time,cause)~cov2(X1,tf=qFun)+cov2(X2,tf=sqFun),data=d,cause=1) ## additional arguments for crr f6<- FGR(Hist(time,cause)~X1+X2,data=d, cause=1,gtol=1e-5) f6 f6a<- FGR(Hist(time,cause)~X1+X2,data=d, cause=1,gtol=0.1) f6a ``` ``` -------------------------------- ### Simulate Competing Risks Data and Fit Model Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Generates simulated data with multiple competing risks using the lava package, fits a CSC model, and calculates risk scores. Ensure lava and data.table are installed. ```R m=lava::lvm(~X1+X2+X3) lava::distribution(m, "eventtime1") <- lava::coxWeibull.lvm(scale = 1/100) lava::distribution(m, "eventtime2") <- lava::coxWeibull.lvm(scale = 1/100) lava::distribution(m, "eventtime3") <- lava::coxWeibull.lvm(scale = 1/100) lava::distribution(m, "censtime") <- lava::coxWeibull.lvm(scale = 1/100) lava::regression(m,eventtime2~X3)=1.3 m <- lava::eventTime(m, time ~ min(eventtime1 = 1, eventtime2 = 2, eventtime3 = 3, censtime = 0), "event") set.seed(101) dcr=as.data.table(lava::sim(m,101)) fit = CSC(Hist(time,event)~X1+X2+X3,data=dcr) scoreobj=Score(list("my model"=fit), formula=Hist(time,event)~1, data=dcr,plots="box",times=5,null.model=FALSE) boxplot(scoreobj) ``` -------------------------------- ### Compare Predicted Probabilities Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Compare predicted probabilities from two different model fits using predictRisk. This example compares a cause-specific hazard model with an all-cause mortality hazard model. ```R plot(predictRisk(fit1,times=500,cause=1,newdata=Melanoma), predictRisk(fit1a,times=500,cause=1,newdata=Melanoma)) ``` -------------------------------- ### simsynth Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Simulating from a synthesized object. ```APIDOC ## simsynth ### Description Simulating from a synthesized object ### Usage ```R simsynth(object, n = 200, drop.latent = FALSE, ...) ``` ### Arguments `object` | generated with `synthesize` `n` | sample size `drop.latent` | if `TRUE` remove the latent event times from the resulting data set. `...` | additional arguments passed on to `lava::sim` ``` -------------------------------- ### Competing Risk Outcome Risk Regression Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Example of fitting and scoring models for competing risks outcomes. ```APIDOC ## Competing Risk Outcome Risk Regression ### Description This section demonstrates fitting Fine-Gray (FGR) and Cause-Specific Cox (CSC) models and then scoring them using the `Score` function for competing risks outcomes. ### Method `FGR`, `CSC`, `Score`, `plotRisk` ### Endpoint N/A (R function usage) ### Parameters N/A (R function usage) ### Request Example ```R library(prodlim) library(survival) set.seed(8) learndat = sampleData(80, outcome = "competing.risk") testdat = sampleData(140, outcome = "competing.risk") m1 = FGR(Hist(time, event) ~ X2 + X7 + X9, data = learndat, cause = 1) m2 = CSC(Hist(time, event) ~ X2 + X7 + X9, data = learndat, cause = 1) xcr = Score(list("FGR" = m1, "CSC" = m2), formula = Hist(time, event) ~ 1, data = testdat, summary = "risks", null.model = 0L, times = c(3, 5)) plotRisk(xcr, times = 3) ``` ### Response N/A (R function usage) ### Response Example N/A (R function usage) ``` -------------------------------- ### Fit GLMnet Models with Formula Interface Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Demonstrates fitting penalized regression models using the GLMnet function with a formula interface. Shows how to use special terms like `unpenalized`, `pen`, and `rcs` for variable selection and regularization. ```R library(glmnet) library(riskRegression) library(survival) data(Melanoma) fit <- GLMnet(Surv(time,status==1)~pen(invasion,4)+epicel+ulcer+logthick+pen(sex,0)+age, data=Melanoma) ``` -------------------------------- ### Binary Outcome Risk Regression Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Example of fitting and scoring a logistic regression model for binary outcomes. ```APIDOC ## Binary Outcome Risk Regression ### Description This section demonstrates fitting a logistic regression model (`glm`) and then scoring it using the `Score` function for binary outcomes. ### Method `glm`, `Score`, `plotRisk` ### Endpoint N/A (R function usage) ### Parameters N/A (R function usage) ### Request Example ```R set.seed(10) learndat = sampleData(40, outcome = "binary") testdat = sampleData(40, outcome = "binary") lr1 = glm(Y ~ X1 + X2 + X7 + X9, data = learndat, family = "binomial") lr2 = glm(Y ~ X3 + X5 + X6, data = learndat, family = "binomial") xb = Score(list("LR(X1+X2+X7+X9)" = lr1, "LR(X3+X5+X6)" = lr2), formula = Y ~ 1, data = testdat, summary = "risks", null.model = 0L) plotRisk(xb) ``` ### Response N/A (R function usage) ### Response Example N/A (R function usage) ``` -------------------------------- ### Survival Outcome Risk Regression Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Example of fitting and scoring Cox proportional hazards models for survival outcomes. ```APIDOC ## Survival Outcome Risk Regression ### Description This section demonstrates fitting Cox proportional hazards models (`coxph`) and then scoring them using the `Score` function for survival outcomes. ### Method `coxph`, `Score`, `plotRisk` ### Endpoint N/A (R function usage) ### Parameters N/A (R function usage) ### Request Example ```R library(survival) set.seed(10) learndat = sampleData(40, outcome = "survival") testdat = sampleData(40, outcome = "survival") cox1 = coxph(Surv(time, event) ~ X1 + X2 + X7 + X9, data = learndat, x = TRUE) cox2 = coxph(Surv(time, event) ~ X3 + X5 + X6, data = learndat, x = TRUE) xs = Score(list("Cox(X1+X2+X7+X9)" = cox1, "Cox(X3+X5+X6)" = cox2), formula = Surv(time, event) ~ 1, data = testdat, summary = "risks", null.model = 0L, times = c(3, 5, 6)) plotRisk(xs, times = 5) ``` ### Response N/A (R function usage) ### Response Example N/A (R function usage) ``` -------------------------------- ### Get Cox model strata names Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Extracts the names of the strata defined within a fitted Cox model. ```R coxStrataLevel(object) ## S3 method for class 'coxph' coxStrataLevel(object) ## S3 method for class 'cph' coxStrataLevel(object) ## S3 method for class 'phreg' coxStrataLevel(object) ## S3 method for class 'prodlim' coxStrataLevel(object) ``` -------------------------------- ### Kaplan Meier Estimation with predictCox Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Demonstrates how to use predictCox for Kaplan-Meier estimation, including handling of ties and stratified models. ```APIDOC ## Kaplan Meier Estimation with predictCox ### Description This section illustrates the use of `predictCox` for Kaplan-Meier (KM) survival estimates, covering scenarios with and without tied event times, as well as stratified KM. ### Method Not applicable (function documentation) ### Endpoint Not applicable (function documentation) ### Parameters None specific to this documentation section. ### Request Example ```R library(survival) library(data.table) # Generate sample data set.seed(10) d <- sampleData(50, outcome="survival") nd <- sampleData(5, outcome="survival") # KM without ties fit.KM <- coxph(Surv(time, event) ~ 1, data = d, x = TRUE, y = TRUE) ePL.KM <- predictCox(fit.KM, product.limit = TRUE) as.data.table(ePL.KM) # KM with ties (using Efron's method for baseline hazard) fit.KM.ties <- coxph(Surv(time.round, event) ~ 1, data = d, x = TRUE, y = TRUE, ties = "breslow") ePL.KM.ties <- predictCox(fit.KM, product.limit = TRUE) # Stratified KM fit.SKM <- coxph(Surv(time, event) ~ strata(X2), data = d, x = TRUE, y = TRUE) ePL.SKM <- predictCox(fit.SKM, product.limit = TRUE) print(ePL.SKM) ``` ### Response #### Success Response (200) Returns a data table or list containing survival probabilities and potentially other related metrics for KM estimates. #### Response Example ```json { "time": [1, 2, 3], "survival": [0.95, 0.90, 0.85], "cumhazard": [0.05, 0.10, 0.15] } ``` ``` -------------------------------- ### simPBC Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Simulate data alike the pbc data from the survival package. ```APIDOC ## simPBC ### Description This function can be used to simulate data alike the pbc data from the survival package. ### Usage ```R simPBC(n) ``` ### Arguments `n` | Sample size ### Details using lava to synthesize data ### Value The simulated data. ### Author(s) Thomas A. Gerds ### Examples ```R library(survival) library(lava) # simulate data alike pbc data set.seed(98) d=simPBC(847) d$protimegrp1 <- d$protimegrp=="10-11" d$protimegrp2 <- d$protimegrp=">11" d$sex <- factor(d$sex,levels=0:1,labels=c("m","f")) sF1 <- survreg(Surv(time,event)~sex+age+logbili+protimegrp1+protimegrp2+stage3+stage4,data=d) coxF1 <- coxph(Surv(time,event)~sex+age+logbili+protimegrp1+protimegrp2+stage3+stage4,data=d) # load real pbc data data(pbc,package="survival") pbc <- na.omit(pbc[,c("time","status","age","sex","stage","bili","protime","trt")]) pbc$stage <- factor(pbc$stage) levels(pbc$stage) <- list("1/2"=c(1,2),"3"=3,"4"=4) pbc$logbili <- log(pbc$bili) pbc$logprotime <- log(pbc$protime) pbc$stage3 <- 1*(pbc$stage=="3") pbc$stage4 <- 1*(pbc$stage=="4") pbc$protimegrp <- cut(pbc$protime,c(-Inf,10,11,Inf),labels=c("<=10","10-11",">11")) pbc$protimegrp1 <- pbc$protimegrp=="10-11" pbc$protimegrp2 <- pbc$protimegrp=">11" form1=Surv(time,status==1)~sex+age+logbili+protimegrp1+protimegrp2+stage3+stage4 F1 <- survival::survreg(form1,data=pbc) form2=Surv(time,status==2)~sex+age+logbili+protimegrp1+protimegrp2+stage3+stage4 F2 <- survival::survreg(form1,data=pbc) sF2 <- survreg(Surv(time,status==2)~sex+age+logbili+protimegrp1+protimegrp2+stage3+stage4, data=d) G <- survreg(Surv(time,status==0)~sex+age+logbili+protimegrp1+protimegrp2+stage3+stage4, data=pbc) sG <- survreg(Surv(time,status==0)~sex+age+logbili+protimegrp1+protimegrp2+stage3+stage4, data=d) # compare fits in real and simulated pbc data cbind(coef(F1),coef(sF1)) cbind(coef(F2),coef(sF2)) cbind(coef(G),coef(sG)) cbind(coef(glm(protimegrp1~age+sex+logbili,data=pbc,family="binomial")), cof(glm(protimegrp1~age+sex+logbili,data=d,family="binomial"))) cbind(coef(lm(logbili~age+sex,data=pbc)),coef(lm(logbili~age+sex,data=d))) ``` ``` -------------------------------- ### Fit and Plot Absolute Risk Regression Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Example of fitting an absolute risk regression model using the Melanoma dataset. ```R library(prodlim) data(Melanoma,package="riskRegression") ## tumor thickness on the log-scale Melanoma$logthick <- log(Melanoma$thick) # Single binary factor ## absolute risk regression library(survival) library(prodlim) fit.arr <- ARR(Hist(time,status)~sex,data=Melanoma,cause=1) print(fit.arr) # show predicted cumulative incidences plot(fit.arr,col=3:4,newdata=data.frame(sex=c("Female","Male"))) ``` -------------------------------- ### Perform Permutation Testing for ATE Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html This script demonstrates a permutation test workflow for an ate object, involving iterative data resampling and statistic calculation. ```R n.sim <- 250 stats.perm <- vector(mode = "list", length = n.sim) pb <- txtProgressBar(max = n.sim, style=3) treatVar <- ateFit$variables["treatment"] for(iSim in 1:n.sim){ ## iSim <- 1 iData <- copy(dtS) iIndex <- sample.int(NROW(iData), replace = FALSE) iData[, c(treatVar) := .SD[[treatVar]][iIndex]] iFit <- update(fit, data = iData) iAteSim <- ate(iFit, data = iData, treatment = unname(treatVar), times = seqTime, verbose = FALSE) iStatistic <- iAteSim$diffRisk[,estimate/se] stats.perm[[iSim]] <- cbind(iAteSim$diffRisk[,.(max = max(iStatistic), L2 = sum(iStatistic^2), sum = sum(iStatistic))], sim = iSim) stats.perm[[iSim]]$maxC <- stats.perm[[iSim]]$max - max(statistic) stats.perm[[iSim]]$L2C <- stats.perm[[iSim]]$L2 - sum(statistic^2) stats.perm[[iSim]]$sumC <- stats.perm[[iSim]]$sum - sum(statistic) setTxtProgressBar(pb, iSim) } dtstats.perm <- do.call(rbind,stats.perm) dtstats.perm[,.(max = mean(.SD$maxC>=0), L2 = mean(.SD$L2C>=0), sum = mean(.SD$sumC>=0))] ``` -------------------------------- ### Define confint method for wglm objects Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html S3 method signature for calculating confidence intervals for IPCW logistic regression models. ```R ## S3 method for class 'wglm' confint(object, parm = NULL, level = 0.95, times = NULL, type = "robust", ...) ``` -------------------------------- ### predictCox Function Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Routine to get baseline hazards and subject specific hazards as well as survival probabilities from a survival::coxph or rms::cph object. ```APIDOC ## predictCox ### Description Routine to get baseline hazards and subject specific hazards as well as survival probabilities from a survival::coxph or rms::cph object. ### Parameters - **object** (object) - Required - The fitted Cox regression model object obtained with coxph or cph. - **times** (numeric vector) - Required - Time points at which to return the estimated hazard/cumulative hazard/survival. - **newdata** (data.frame or data.table) - Optional - Predictor variables defining subject specific predictions. - **centered** (logical) - Optional - If TRUE return prediction at the mean values of the covariates. - **type** (character vector) - Optional - The type of predicted value: "hazard", "cumhazard", or "survival". - **keep.strata** (logical) - Optional - If TRUE add the strata to the output. - **keep.times** (logical) - Optional - If TRUE add the evaluation times to the output. - **keep.newdata** (logical) - Optional - If TRUE add the value of the covariates used to make the prediction. - **se** (logical) - Optional - If TRUE compute and add the standard errors. - **band** (logical) - Optional - If TRUE compute and add the quantiles for the confidence bands. - **iid** (logical) - Optional - If TRUE compute and add the influence function. - **confint** (logical) - Optional - If TRUE compute and add the confidence intervals/bands. - **diag** (logical) - Optional - If FALSE compute for all observations at all times, otherwise only for the i-th observation at the i-th time. - **average.iid** (logical) - Optional - If TRUE add the average of the influence function over newdata. - **product.limit** (logical) - Optional - If TRUE the survival is computed using the product limit estimator. - **store** (vector) - Optional - Memory management settings for predictions and influence functions. ``` -------------------------------- ### Compute confidence intervals for CSC model predictions Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Demonstrates generating data, fitting a stratified CSC model, and computing confidence intervals for individual risks with and without transformations. ```R library(survival) library(prodlim) #### generate data #### set.seed(10) d <- sampleData(100) #### estimate a stratified CSC model ### fit <- CSC(Hist(time,event)~ X1 + strata(X2) + X6, data=d) #### compute individual specific risks fit.pred <- predict(fit, newdata=d[1:3], times=c(3,8), cause = 1, se = TRUE, iid = TRUE, band = TRUE) fit.pred ## check confidence intervals newse <- fit.pred$absRisk.se/(-fit.pred$absRisk*log(fit.pred$absRisk)) cbind(lower = as.double(exp(-exp(log(-log(fit.pred$absRisk)) + 1.96 * newse))), upper = as.double(exp(-exp(log(-log(fit.pred$absRisk)) - 1.96 * newse))) ) #### compute confidence intervals without transformation confint(fit.pred, absRisk.transform = "none") cbind(lower = as.double(fit.pred$absRisk - 1.96 * fit.pred$absRisk.se), upper = as.double(fit.pred$absRisk + 1.96 * fit.pred$absRisk.se) ) ``` -------------------------------- ### Simulate from synthesized object Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Generates data from an object created by the synthesize function. ```R simsynth(object, n = 200, drop.latent = FALSE, ...) ``` -------------------------------- ### Parallel processing with future Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Uses future and foreach for parallel bootstrapping in Score. ```R library(riskRegression) library(future) library(foreach) library(doFuture) library(survival) plan(multiprocess, workers = availableCores()) registerDoFuture() set.seed(10) trainSurv <- sampleData(400,outcome="survival") cox1 = coxph(Surv(time,event)~X1+X2+X7+X9,data=trainSurv, y=TRUE, x = TRUE) x1 = Score(list("Cox(X1+X2+X7+X9)"=cox1), formula=Surv(time,event)~1,data=trainSurv, times=c(5,8), parallel = "as.registered", split.method="bootcv",B=100) ``` -------------------------------- ### Predict Event Risk Source: https://cran.r-project.org/web/packages/riskRegression/refman/riskRegression.html Predict the event risk for a specific cause and time point using a fitted model. This example uses the model 'fit1b' and predicts for cause 1 at time 100. ```R predict(fit1b,cause=1,times=100,newdata=Melanoma) ```