### Install flexsurv Development Version Source: https://github.com/chjackson/flexsurv/blob/master/README.md Install the latest development version of flexsurv directly from GitHub using the devtools package. Ensure devtools is installed first. ```r install.packages("devtools") # if devtools not already installed devtools::install_github('chjackson/flexsurv-dev') ``` -------------------------------- ### Install flexsurv Package Source: https://context7.com/chjackson/flexsurv/llms.txt Installs the stable CRAN version or the development version from GitHub. ```r install.packages("flexsurv") ``` ```r devtools::install_github("chjackson/flexsurv-dev") ``` -------------------------------- ### Calculate quantiles using qgeneric Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/qgeneric.html This example demonstrates how to use qgeneric to find quantiles for a normal distribution. Ensure that all distribution parameters are explicitly named. ```R qgeneric(pnorm, c(0.025, 0.975), mean=0, sd=1) # must name the arguments ``` -------------------------------- ### Install flexsurv from CRAN Source: https://github.com/chjackson/flexsurv/blob/master/README.md Use this command to install the stable version of the flexsurv package from CRAN. ```r install.packages("flexsurv") ``` -------------------------------- ### Fit Custom Distribution (EV) using eha package Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/flexsurvreg.html Demonstrates fitting a custom Extreme Value (EV) distribution using definitions from the 'eha' package. Requires the 'eha' package to be installed and loaded. ```R if (require("eha")) { custom.ev <- list(name="EV", pars=c("shape","scale"), location="scale", transforms=c(log, log), inv.transforms=c(exp, exp), inits=function(t){ c(1, median(t)) }) flexsurvreg(formula = Surv(futime, fustat) ~ 1, data = ovarian, dist=custom.ev) lines(fitev, col="purple", col.ci="purple") } ``` -------------------------------- ### fmixmsm Constructor Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/fmixmsm.html Constructs a mixture multi-state model based on flexsurvmix. It takes named arguments, where each argument is a fitted model from flexsurvmix, and the argument name specifies the starting state. ```APIDOC ## fmixmsm ### Description Constructor for a mixture multi-state model based on flexsurvmix. ### Usage fmixmsm(...) ### Arguments * `...`: Named arguments. Each argument should be a fitted model as returned by `[flexsurvmix](flexsurvmix.html)`. The name of each argument names the starting state for that model. ### Value A list of `[flexsurvmix](flexsurvmix.html)` objects, with the following attribute(s): * `pathways`: A list of all potential pathways until absorption, for models without cycles. For models with cycles this will have an element `has_cycle=TRUE`, plus the pathways discovered before the function found the cycle and gave up. ``` -------------------------------- ### Fit a flexsurvreg model and augment data Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/augment.flexsurvreg.html This example demonstrates fitting an exponential survival model using `flexsurvreg` and then augmenting the original dataset with predictions and residuals using `augment`. The `.resid` column is included because the original data was provided. ```R fit <- flexsurvreg(formula = Surv(futime, fustat) ~ age, data = ovarian, dist = "exp") augment(fit, data = ovarian) ``` -------------------------------- ### totlos.fs Function Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/totlos.fs.html Calculates the expected amount of time spent in each state of a multi-state process, starting from a given state, up to a specified maximum time. ```APIDOC ## totlos.fs ### Description Calculates the matrix whose (r,s) entry is the expected amount of time spent in state s for a time-inhomogeneous, continuous-time Markov multi-state process that starts in state r, up to a maximum time t. This is defined as the integral of the corresponding transition probability up to that time. ### Usage ```r totlos.fs( x, trans = NULL, t = 1, newdata = NULL, ci = FALSE, tvar = "trans", sing.inf = 1e+10, B = 1000, cl = 0.95, ... ) ``` ### Arguments * `x`: A model fitted with `flexsurvreg`. This must be a Markov / clock-forward model, but can be time-inhomogeneous. `x` can also be a list of models. * `trans`: Matrix indicating allowed transitions. See `msfit.flexsurvreg`. * `t`: Time or vector of times to predict up to. Must be finite. * `newdata`: A data frame specifying the values of covariates in the fitted model, other than the transition number. * `ci`: Logical. If TRUE, return a confidence interval calculated by simulating from the asymptotic normal distribution of the maximum likelihood estimates. * `tvar`: Variable in the data representing the transition type. Not required if `x` is a list of models. * `sing.inf`: Workaround for singularities in the observed hazard. Assumed to be a large finite number at the time of singularity. * `B`: Number of simulations from the normal asymptotic distribution used to calculate variances. * `cl`: Width of symmetric confidence intervals, relative to 1. * `...`: Arguments passed to `ode` in deSolve. ### Value The matrix of lengths of stay \(T(t)\), if `t` is of length 1, or a list of matrices if `t` is longer. If `ci=TRUE`, each element has attributes `"lower"` and `"upper"` giving matrices of the corresponding confidence limits. The result also has an attribute `P` giving the transition probability matrices. ### Details This is computed by solving a second order extension of the Kolmogorov forward differential equation numerically. The equation is expressed as a linear system and solved for \(T(t)\) and \(P(t)\) simultaneously, where \(T(t)\) is the matrix of total lengths of stay, \(P(t)\) is the transition probability matrix for time \(t\), and \(Q(t)\) is the transition hazard or intensity as a function of \(t\). The initial conditions are \(T(0) = 0\) and \(P(0) = I\). Note that the package `msm` has a similar method `totlos.msm`. `totlos.fs` should give the same results as `totlos.msm` when the time-to-event distribution is exponential for all transitions and the model is time-homogeneous. ``` -------------------------------- ### Simulate Multi-State Survival Data with pmatrix.simfs Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/pmatrix.simfs.html Use pmatrix.simfs to simulate the transition probability matrix for a multi-state model. This example demonstrates simulating probabilities at different time points (t=5 and t=10) using an exponential distribution. The results should converge to those from pmatrix.fs for exponential distributions as the number of simulations increases. ```r bexp <- flexsurvreg(Surv(years, status) ~ trans, data=bosms3, dist="exp") tmat <- rbind(c(NA,1,2),c(NA,NA,3),c(NA,NA,NA)) # more likely to be dead (state 3) as time moves on, or if start with # BOS (state 2) pmatrix.simfs(bexp, t=5, trans=tmat) #> 1 2 3 #> 1 0.29456 0.26691 0.43853 #> 2 0.00000 0.26781 0.73219 #> 3 0.00000 0.00000 1.00000 pmatrix.simfs(bexp, t=10, trans=tmat) #> 1 2 3 #> 1 0.08806 0.15161 0.76033 #> 2 0.00000 0.07006 0.92994 #> 3 0.00000 0.00000 1.00000 # these results should converge to those in help(pmatrix.fs), as M # increases here and ODE solving precision increases there, since with # an exponential distribution, the semi-Markov model is the same as the # Markov model. ``` -------------------------------- ### pmatrix.fs() / totlos.fs() — Transition probabilities and total length of stay Source: https://context7.com/chjackson/flexsurv/llms.txt Computes the transition probability matrix (probability of being in each state at time t, given starting state) and expected total time spent in each state, directly from a list of transition-specific flexsurvreg models, without requiring the mstate package. ```APIDOC ## pmatrix.fs() / totlos.fs() — Transition probabilities and total length of stay ### Description Computes the transition probability matrix (probability of being in each state at time `t`, given starting state) and expected total time spent in each state, directly from a list of transition-specific `flexsurvreg` models, without requiring the `mstate` package. ### Method ```r pmatrix.fs(fits, trans, t, start, ...) totlos.fs(fits, trans, t, start, ...) ``` ### Parameters - **fits**: A list of fitted flexsurvreg objects, one for each transition. - **trans**: A transition matrix defining the states and possible transitions. - **t**: The time at which to compute the transition probabilities or total length of stay. - **start**: The starting state. - **...**: Additional arguments. ### Request Example ```r library(flexsurv) data(bosms3) tmat <- rbind(c(NA, 1, 2), c(NA, NA, 3), c(NA, NA, NA)) # Fit separate models per transition fits <- vector("list", 3) for (i in 1:3) { fits[[i]] <- flexsurvreg( Surv(years, status) ~ 1, data = bosms3[bosms3$trans == i, ], dist = "weibull" ) } # Transition probability matrix at t=5 starting from state 1 pmat <- pmatrix.fs(fits, trans = tmat, t = 5, start = 1) pmat # to # from State 1 State 2 State 3 # [starting] 0.47 0.13 0.40 # Expected total length of stay in each state over [0, 10] totlos.fs(fits, trans = tmat, t = 10, start = 1) ``` ``` -------------------------------- ### Package Overview Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/index.html Information about the flexsurv package. ```APIDOC ## Package Overview ### `flexsurv-package` / `flexsurv` This package, `flexsurv`, provides tools for flexible parametric survival and multi-state models. ``` -------------------------------- ### Getting Results from Survival Models Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/index.html Functions for extracting and summarizing results from fitted survival models. ```APIDOC ## summary(flexsurvreg) ### Description Summaries of fitted flexible survival models. ### Method Call ### Endpoint summary.flexsurvreg ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## standsurv() ### Description Marginal survival and hazards of fitted flexsurvreg models. ### Method Call ### Endpoint standsurv ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## coef(flexsurvreg) ### Description Extract model coefficients from fitted flexible survival models. ### Method Call ### Endpoint coef.flexsurvreg ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## normboot.flexsurvreg() ### Description Simulate from the asymptotic normal distribution of parameter estimates. ### Method Call ### Endpoint normboot.flexsurvreg ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## hr_flexsurvreg() ### Description Hazard ratio as a function of time from a parametric survival model. ### Method Call ### Endpoint hr_flexsurvreg ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## vcov(flexsurvreg) ### Description Variance-covariance matrix from a flexsurvreg model. ### Method Call ### Endpoint vcov.flexsurvreg ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## simulate(flexsurvreg) ### Description Simulate censored time-to-event data from a fitted flexsurvreg model. ### Method Call ### Endpoint simulate.flexsurvreg ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## plot(flexsurvreg) ### Description Plots of fitted flexible survival models. ### Method Call ### Endpoint plot.flexsurvreg ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## lines(flexsurvreg) ### Description Add fitted flexible survival curves to a plot. ### Method Call ### Endpoint lines.flexsurvreg ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## plot(standsurv) ### Description Plot standardized metrics from a fitted flexsurv model. ### Method Call ### Endpoint plot.standsurv ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## summary(flexsurvrtrunc) ### Description Summarise quantities of interest from fitted flexsurvrtrunc models. ### Method Call ### Endpoint summary.flexsurvrtrunc ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## plot(survrtrunc) ### Description Plot nonparametric estimates of survival from right-truncated data. ### Method Call ### Endpoint plot.survrtrunc ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` ```APIDOC ## lines(survrtrunc) ### Description Add nonparametric estimates of survival from right-truncated data to a plot. ### Method Call ### Endpoint lines.survrtrunc ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` -------------------------------- ### Plot Survival Curves Source: https://github.com/chjackson/flexsurv/blob/master/docs/articles/standsurv.html Plots survival curves based on extracted predictions. This example combines predictions from the flexsurv model with Kaplan-Meier estimates for comparison. ```R ggplot() + geom_line(aes(x=time, y=est, color = group2), data=predictions) + geom_step(aes(x=time, y=surv, group=strata), data=kmsurvplot$data.survplot) ``` -------------------------------- ### Calculate Transition Probabilities and Total Length of Stay Source: https://context7.com/chjackson/flexsurv/llms.txt Use pmatrix.fs and totlos.fs to compute the transition probability matrix and expected total time spent in each state, respectively. These functions work directly from a list of transition-specific flexsurvreg models and do not require the mstate package. ```r library(flexsurv) data(bosms3) tmat <- rbind(c(NA, 1, 2), c(NA, NA, 3), c(NA, NA, NA)) ``` ```r # Fit separate models per transition fits <- vector("list", 3) for (i in 1:3) { fits[[i]] <- flexsurvreg( Surv(years, status) ~ 1, data = bosms3[bosms3$trans == i, ], dist = "weibull" ) } ``` ```r # Transition probability matrix at t=5 starting from state 1 pmat <- pmatrix.fs(fits, trans = tmat, t = 5, start = 1) pmat ``` ```r # Expected total length of stay in each state over [0, 10] totlos.fs(fits, trans = tmat, t = 10, start = 1) ``` -------------------------------- ### Calculate RMST using rmst_lnorm Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/rmst_generic.html Example of calculating restricted mean survival time using the rmst_lnorm function for a log-normal distribution. Ensure all arguments are named explicitly. ```r rmst_lnorm(500, start=250, meanlog=7.4225, sdlog = 1.1138) #> [1] 237.8849 ``` -------------------------------- ### Generalized Gamma Distribution Functions (Original Parameterisation) Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/GenGamma.orig.html Provides functions for the density (dgengamma.orig), distribution function (pgengamma.orig), cumulative hazard (Hgengamma.orig), hazard (hgengamma.orig), quantile function (qgengamma.orig), and random generation (rgengamma.orig) for the generalized gamma distribution using the original parameterization. ```APIDOC ## Functions for Generalized Gamma Distribution (Original Parameterisation) ### Description These functions provide various statistical calculations for the generalized gamma distribution using its original parameterization. ### Usage ``` dgengamma.orig(x, shape, scale = 1, k, log = FALSE) pgengamma.orig(q, shape, scale = 1, k, lower.tail = TRUE, log.p = FALSE) Hgengamma.orig(x, shape, scale = 1, k) hgengamma.orig(x, shape, scale = 1, k) qgengamma.orig(p, shape, scale = 1, k, lower.tail = TRUE, log.p = FALSE) rgengamma.orig(n, shape, scale = 1, k) ``` ### Arguments * `x`, `q`: Vector of quantiles. * `shape`: Vector of Weibull shape parameters. * `scale`: Vector of scale parameters (default is 1). * `k`: Vector of Gamma shape parameters. * `log`: Logical; if TRUE, probabilities p are given as log(p). * `log.p`: Logical; if TRUE, probabilities p are given as log(p). * `lower.tail`: Logical; if TRUE (default), probabilities are P(X <= x), otherwise, P(X > x). * `p`: Vector of probabilities. * `n`: Number of observations to generate. If `length(n) > 1`, the length is taken to be the number required. ### Value * `dgengamma.orig`: Density function. * `pgengamma.orig`: Distribution function. * `Hgengamma.orig`: Cumulative hazard function. * `hgengamma.orig`: Hazard function. * `qgengamma.orig`: Quantile function. * `rgengamma.orig`: Random deviates generation. ``` -------------------------------- ### Custom Integration Options for flexsurvmix Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/flexsurvmix.html Pass custom options to the integrate function when providing a custom density or hazard without its cumulative version. Example shows setting a relative tolerance. ```R integ.opts = list(rel.tol=1e-12) ``` -------------------------------- ### Fit Custom Distribution (Exponential) by Supplying Hazard Function Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/flexsurvreg.html Illustrates fitting a custom exponential distribution by providing only the hazard function. This method is useful when the full density or survival functions are not readily available. An error is shown when the distribution is not found, followed by a successful fit using the built-in 'exp' distribution. ```R hexp2 <- function(x, rate=1){ rate } # exponential distribution hexp2 <- Vectorize(hexp2) custom.exp2 <- list(name="exp2", pars=c("rate"), location="rate", transforms=c(log), inv.transforms=c(exp), inits=function(t)1/mean(t)) flexsurvreg(Surv(futime, fustat) ~ 1, data = ovarian, dist=custom.exp2) ``` ```R flexsurvreg(Surv(futime, fustat) ~ 1, data = ovarian, dist="exp") ``` -------------------------------- ### Calculate total time in states Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/totlos.fs.html Fit an exponential model and then calculate the total time spent in each state at t=10 years. This example demonstrates the basic usage of totlos.fs with a single time point. ```R bexp <- flexsurvreg(Surv(Tstart, Tstop, status) ~ trans, data=bosms3, dist="exp") tmat <- rbind(c(NA,1,2),c(NA,NA,3),c(NA,NA,NA)) totlos.fs(bexp, t=10, trans=tmat) ``` -------------------------------- ### Simulate Right-Truncated Survival Data Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/flexsurvrtrunc.html Simulates time to an initial event (X) and time between initial and final event (T) for right-truncated survival data. This is a common setup for demonstrating survival analysis with truncation. ```r set.seed(1) ## simulate time to initial event X <- rexp(1000, 0.2) ## simulate time between initial and final event T <- rgamma(1000, 2, 10) ``` -------------------------------- ### fmixmsm Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/index.html Constructor for a mixture multi-state model based on flexsurvmix. ```APIDOC ## fmixmsm() ### Description Constructor for a mixture multi-state model based on flexsurvmix. ### Method Function Call ### Endpoint fmixmsm() ### Parameters None explicitly documented. ### Request Example ``` fmixmsm(formula, data, ...) ``` ### Response None explicitly documented. ``` -------------------------------- ### Generate Tidymodels-Compatible Predictions with predict.flexsurvreg Source: https://context7.com/chjackson/flexsurv/llms.txt Use predict.flexsurvreg to get predictions in a tidy tibble format, compatible with the tidymodels ecosystem. Supports various outcome types and returns list-columns for multiple time points. ```r library(flexsurv) fit <- flexsurvreg(Surv(futime, fustat) ~ rx, data = ovarian, dist = "weibull") nd <- data.frame(rx = 1:2) # Mean survival time predict(fit, newdata = nd, type = "response") ``` ```r # Survival probabilities at specified times (returns list-column) predict(fit, newdata = nd, type = "survival", times = c(365, 730)) ``` ```r # Quantiles of the survival distribution predict(fit, newdata = nd, type = "quantile", p = c(0.25, 0.5, 0.75)) ``` ```r # With confidence intervals predict(fit, newdata = nd, type = "survival", times = c(365, 730), conf.int = TRUE, conf.level = 0.95) ``` -------------------------------- ### Summarize flexsurvreg model with glance Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/glance.flexsurvreg.html Use `glance` on a fitted `flexsurvreg` object to get a tibble with model summaries like N, events, logLik, AIC, and BIC. Ensure the model is fitted first. ```R fitg <- flexsurvreg(formula = Surv(futime, fustat) ~ age, data = ovarian, dist = "gengamma") glance(fitg) ``` -------------------------------- ### Simulate parameter estimates with normboot.flexsurvreg Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/normboot.flexsurvreg.html Simulate parameter estimates from the asymptotic normal distribution for a fitted flexsurvreg model. Use `newdata` to specify covariate values as a list, or `X` to provide them as a matrix. ```R fite <- flexsurvreg(Surv(futime, fustat) ~ age, data = ovarian, dist="exp") normboot.flexsurvreg(fite, B=10, newdata=list(age=50)) ``` ```R normboot.flexsurvreg(fite, B=10, X=matrix(50,nrow=1)) ``` -------------------------------- ### Define and use custom survival distributions in flexsurvreg Source: https://context7.com/chjackson/flexsurv/llms.txt Supply a list to the `dist` argument in `flexsurvreg` to define custom distributions. This requires specifying distribution name, parameters, transformations, and initialization functions. The distribution must have a density or hazard function available in the environment. ```R library(flexsurv) library(eha) # provides dEV, pEV # Define a custom extreme value distribution custom_ev <- list( name = "EV", pars = c("shape", "scale"), location = "scale", transforms = c(log, log), inv.transforms = c(exp, exp), inits = function(t) c(1, median(t)) ) fit_ev <- flexsurvreg(Surv(futime, fustat) ~ 1, data = ovarian, dist = custom_ev) fit_ev # Custom distribution defined via hazard function only (exponential example) hexp2 <- Vectorize(function(x, rate = 1) rate) custom_exp2 <- list( name = "exp2", pars = "rate", location = "rate", transforms = list(log), inv.transforms = list(exp), inits = function(t) 1 / mean(t) ) fit_custom <- flexsurvreg(Surv(futime, fustat) ~ 1, data = ovarian, dist = custom_exp2) # Should match: fit_exp <- flexsurvreg(Surv(futime, fustat) ~ 1, data = ovarian, dist = "exp") cbind(fit_custom$res, fit_exp$res) ``` -------------------------------- ### coef.flexsurvreg Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/coef.flexsurvreg.html Extract model coefficients from fitted flexible survival models. This presents all parameter estimates, transformed to the real line if necessary. For example, shape or scale parameters, which are constrained to be positive, are returned on the log scale. ```APIDOC ## coef.flexsurvreg ### Description Extract model coefficients from fitted flexible survival models. This presents all parameter estimates, transformed to the real line if necessary. For example, shape or scale parameters, which are constrained to be positive, are returned on the log scale. ### Usage ``` coef(object, ...) ``` ### Arguments * `object` (flexsurvreg or flexsurvspline object) - Output from `flexsurvreg` or `flexsurvspline`, representing a fitted survival model object. * `...` - Further arguments passed to or from other methods. Currently unused. ### Value This returns the `mod$res.t[,"est"]` component of the fitted model object `mod`. See `flexsurvreg`, `flexsurvspline` for full documentation of all components. ### Details This matches the behaviour of `coef.default` for standard R model families such as `glm`, where intercepts in regression models are presented on the same scale as the covariate effects. Note that any parameter in a distribution fitted by `flexsurvreg` or `flexsurvreg` may be an intercept in a regression model. ### See Also `flexsurvreg`, `flexsurvspline`. ``` -------------------------------- ### Model Comparison and Accessing Estimates in flexsurvreg Source: https://context7.com/chjackson/flexsurv/llms.txt Compares fitted models using AIC and demonstrates how to access parameter estimates on the natural scale, log-likelihood, coefficients on the transformed scale, and the variance-covariance matrix. ```r # Model comparison via AIC fit_w$AIC fit_gg$AIC # Access parameter estimates on natural scale fit_w$res # Log-likelihood logLik(fit_w) # 'log Lik.' -97.0 (df=3) # Coefficients on log/transformed scale coef(fit_w) # log(shape) log(scale) rx # -0.007614 6.972496 0.443717 # Variance-covariance matrix vcov(fit_w) ``` -------------------------------- ### Calculate RMST using rmst_generic with plnorm Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/rmst_generic.html Example of calculating restricted mean survival time using the generic rmst_generic function with the plnorm distribution. This demonstrates the flexibility of the generic function. Ensure all arguments are named explicitly. ```r rmst_generic(plnorm, 500, start=250, meanlog=7.4225, sdlog = 1.1138) #> [1] 237.8849 # must name the arguments ``` -------------------------------- ### Generalized Gamma to Gamma Equivalence Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/GenGamma.html Illustrates the equivalence between the generalized gamma distribution with Q=sigma and the gamma distribution. This shows how GenGamma can represent the gamma distribution with specific parameter mappings. ```R dgengamma(x, mu, sigma, Q=sigma) = dgamma(x, shape=1/sigma^2, rate=exp(-mu) / sigma^2) ``` -------------------------------- ### Broom-compatible model summaries for flexsurvreg objects Source: https://context7.com/chjackson/flexsurv/llms.txt Use `tidy()`, `glance()`, and `augment()` from the broom package to get model summaries. `tidy()` provides parameter estimates, `glance()` offers model-level statistics, and `augment()` appends residuals and fitted values to the original data. ```R library(flexsurv) library(broom) fit <- flexsurvreg(Surv(futime, fustat) ~ age + rx, data = ovarian, dist = "gengamma") # tidy(): one row per parameter tidy(fit) # # A tibble: 5 × 6 # term estimate std.error statistic p.value conf.low # ... # With confidence intervals and exponentiated covariate effects (time ratios) tidy(fit, conf.int = TRUE, transform = "coefs.exp") # Baseline parameters only, on real (log) scale tidy(fit, pars = "baseline", transform = "baseline.real") # glance(): one row model-level statistics glance(fit) # # A tibble: 1 × 5 # N events logLik AIC BIC # # 26 12 -88.3 186. 193. # augment(): residuals and fitted values appended to data augment(fit) ``` -------------------------------- ### Using built-in flexsurv distribution functions (GenGamma, Weibull, etc.) Source: https://context7.com/chjackson/flexsurv/llms.txt flexsurv provides d/p/q/r/h/H functions for various distributions like generalized gamma, Gompertz, and log-logistic. These functions have a consistent API and support vectorized parameters. The Royston-Parmar spline distribution is also available. ```R library(flexsurv) # Generalized gamma: d/p/q/r/h/H dgengamma(x = 500, mu = 6.5, sigma = 0.8, Q = 0.5) # density pgengamma(q = 500, mu = 6.5, sigma = 0.8, Q = 0.5) # CDF qgengamma(p = 0.5, mu = 6.5, sigma = 0.8, Q = 0.5) # median rgengamma(n = 10, mu = 6.5, sigma = 0.8, Q = 0.5) # random deviates hgengamma(x = 500, mu = 6.5, sigma = 0.8, Q = 0.5) # hazard Hgengamma(x = 500, mu = 6.5, sigma = 0.8, Q = 0.5) # cumulative hazard # Gompertz: rate is the scale (PH) parameter pgompertz(q = 3, shape = 0.1, rate = 0.05, lower.tail = FALSE) # survival # Log-logistic hllogis(x = 2, shape = 1.5, scale = 1.2) # hazard # Royston-Parmar spline distribution (reduces to Weibull when k=0) # gamma = c(gamma0, gamma1): intercept + slope of log cumulative hazard knots <- c(-2, 2) dsurvspline(x = 1, gamma = c(-2, 1.5), knots = knots, scale = "hazard") psurvspline(q = 1, gamma = c(-2, 1.5), knots = knots, scale = "hazard", lower.tail = FALSE) # survival probability hsurvspline(x = 1, gamma = c(-2, 1.5), knots = knots, scale = "hazard") # Natural cubic spline basis matrix (Royston-Parmar parameterisation) basis(knots = c(-2, 0, 2), x = c(-1, 0, 1)) ``` -------------------------------- ### Calculate total time spent in states using totlos.simfs Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/totlos.simfs.html Use totlos.simfs with a fitted flexsurvreg model and a transition matrix to predict time spent in states. The results converge as the time horizon (t) increases. ```R # BOS example in vignette, and in msfit.flexsurvreg bexp <- flexsurvreg(Surv(years, status) ~ trans, data=bosms3, dist="exp") tmat <- rbind(c(NA,1,2),c(NA,NA,3),c(NA,NA,NA)) # predict 4 years spent without BOS, 3 years with BOS, before death # As t increases, this should converge totlos.simfs(bexp, t=10, trans=tmat) #> 1 2 3 #> 3.744657 2.124928 4.130415 totlos.simfs(bexp, t=1000, trans=tmat) #> 1 2 3 #> 4.127463 2.957653 992.914884 ``` -------------------------------- ### Bootstrap confidence intervals for custom quantities using normboot.flexsurvreg() Source: https://context7.com/chjackson/flexsurv/llms.txt Generate bootstrap confidence intervals for custom functions of model parameters. `normboot.flexsurvreg()` simulates parameters from the MLEs' asymptotic normal distribution to create these intervals, extending beyond built-in summaries. ```R library(flexsurv) fit <- flexsurvreg(Surv(futime, fustat) ~ rx, data = ovarian, dist = "weibull") # Draw 1000 bootstrap samples of all parameters boot_samp <- normboot.flexsurvreg(fit, B = 1000) head(boot_samp) # shape scale rx # [1,] 0.8612 1022.432 0.5213 # ... ``` -------------------------------- ### Using Alternative Spline Basis Functions Source: https://context7.com/chjackson/flexsurv/llms.txt Demonstrates fitting a spline model using an alternative orthogonal spline basis from the 'splines2' package. ```r library(flexsurv) # Use alternative orthogonal spline basis (splines2 package) spl2 <- flexsurvspline(Surv(recyrs, censrec) ~ group, data = bc, k = 1, scale = "hazard", spline = "splines2ns") ``` -------------------------------- ### Generalized F Distribution Functions (Original Parameterisation) Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/GenF.orig.html This section details the functions available for the original parameterisation of the generalized F distribution, including density, distribution, quantile, and random generation. ```APIDOC ## dgenf.orig ### Description Calculates the density of the original generalized F distribution. ### Usage ``` dgenf.orig(x, mu = 0, sigma = 1, s1, s2, log = FALSE) ``` ### Arguments * `x` (vector): Vector of quantiles. * `mu` (vector): Vector of location parameters. * `sigma` (vector): Vector of scale parameters. * `s1` (vector): Vector of first F shape parameters. * `s2` (vector): Vector of second F shape parameters. * `log` (logical): If TRUE, probabilities p are given as log(p). ### Value The density of the distribution. ## pgenf.orig ### Description Calculates the distribution function (cumulative density) of the original generalized F distribution. ### Usage ``` pgenf.orig(q, mu = 0, sigma = 1, s1, s2, lower.tail = TRUE, log.p = FALSE) ``` ### Arguments * `q` (vector): Vector of quantiles. * `mu` (vector): Vector of location parameters. * `sigma` (vector): Vector of scale parameters. * `s1` (vector): Vector of first F shape parameters. * `s2` (vector): Vector of second F shape parameters. * `lower.tail` (logical): If TRUE (default), probabilities are P(X <= x), otherwise, P(X > x). * `log.p` (logical): If TRUE, probabilities p are given as log(p). ### Value The distribution function of the distribution. ## Hgenf.orig ### Description Calculates the cumulative hazard function of the original generalized F distribution. ### Usage ``` Hgenf.orig(x, mu = 0, sigma = 1, s1, s2) ``` ### Arguments * `x` (vector): Vector of quantiles. * `mu` (vector): Vector of location parameters. * `sigma` (vector): Vector of scale parameters. * `s1` (vector): Vector of first F shape parameters. * `s2` (vector): Vector of second F shape parameters. ### Value The cumulative hazard function of the distribution. ## hgenf.orig ### Description Calculates the hazard function of the original generalized F distribution. ### Usage ``` hgenf.orig(x, mu = 0, sigma = 1, s1, s2) ``` ### Arguments * `x` (vector): Vector of quantiles. * `mu` (vector): Vector of location parameters. * `sigma` (vector): Vector of scale parameters. * `s1` (vector): Vector of first F shape parameters. * `s2` (vector): Vector of second F shape parameters. ### Value The hazard function of the distribution. ## qgenf.orig ### Description Calculates the quantile function (inverse distribution function) of the original generalized F distribution. ### Usage ``` qgenf.orig(p, mu = 0, sigma = 1, s1, s2, lower.tail = TRUE, log.p = FALSE) ``` ### Arguments * `p` (vector): Vector of probabilities. * `mu` (vector): Vector of location parameters. * `sigma` (vector): Vector of scale parameters. * `s1` (vector): Vector of first F shape parameters. * `s2` (vector): Vector of second F shape parameters. * `lower.tail` (logical): If TRUE (default), probabilities are P(X <= x), otherwise, P(X > x). * `log.p` (logical): If TRUE, probabilities p are given as log(p). ### Value The quantile function of the distribution. ## rgenf.orig ### Description Generates random deviates from the original generalized F distribution. ### Usage ``` rgenf.orig(n, mu = 0, sigma = 1, s1, s2) ``` ### Arguments * `n` (integer): Number of observations. If `length(n) > 1`, the length is taken to be the number required. * `mu` (vector): Vector of location parameters. * `sigma` (vector): Vector of scale parameters. * `s1` (vector): Vector of first F shape parameters. * `s2` (vector): Vector of second F shape parameters. ### Value Randomly generated observations from the distribution. ``` -------------------------------- ### Weibull Distribution Reduction Source: https://github.com/chjackson/flexsurv/blob/master/docs/reference/Survspline.html Demonstrates how dsurvspline can reduce to the dweibull function when specific parameters are used, effectively showing a special case of the spline model. ```R regscale <- 0.786; cf <- 1.82 a <- 1/regscale; b <- exp(cf) dweibull(1, shape=a, scale=b) #> [1] 0.1137858 dsurvspline(1, gamma=c(log(1 / b^a), a)) # should be the same #> [1] 0.1137858 ``` -------------------------------- ### simulate.flexsurvreg() Source: https://context7.com/chjackson/flexsurv/llms.txt Generates simulated time-to-event datasets from a fitted `flexsurvreg` or `flexsurvspline` model, optionally applying right-censoring. Useful for posterior predictive checks, power calculations, and trial simulation. ```APIDOC ## `simulate.flexsurvreg()` — Simulate survival data from a fitted model Generates simulated time-to-event datasets from a fitted `flexsurvreg` or `flexsurvspline` model, optionally applying right-censoring. Useful for posterior predictive checks, power calculations, and trial simulation. ```r library(flexsurv) fit <- flexsurvreg(Surv(futime, fustat) ~ rx, data = ovarian, dist = "weibull") fit2 <- flexsurvspline(Surv(futime, fustat) ~ rx, data = ovarian, k = 2) nd <- data.frame(rx = 1:2) # Single simulation per covariate row (wide format) simulate(fit, seed = 42, newdata = nd) # sim_1_time sim_1_status # 1 1403.58 1 # 2 2095.17 1 # Multiple simulations in tidy (long) format simulate(fit2, nsim = 5, seed = 42, newdata = nd, tidy = TRUE) # Simulate with administrative censoring at t=1000 simulate(fit, nsim = 10, seed = 42, newdata = nd, censtime = 1000, tidy = TRUE) # Simulate from original data with delayed entry simulate(fit, seed = 42, start = 100) ``` ```