### Install survminer from GitHub Source: https://github.com/kassambara/survminer/blob/master/README.md Install the latest development version of survminer from GitHub. Ensure the devtools package is installed first. ```r if(!require(devtools)) install.packages("devtools") devtools::install_github("kassambara/survminer", build_vignettes = FALSE) ``` -------------------------------- ### Install Required Packages Source: https://github.com/kassambara/survminer/blob/master/_autodocs/quick-reference.md Installs essential packages for survival analysis visualization and optional packages for advanced models like flexible parametric models and competing risks. ```r install.packages(c( "ggplot2", "ggpubr", "survival", "gridExtra", "broom", "dplyr", "tidyr", "purrr", "maxstat" )) ``` ```r install.packages(c( "flexsurv", # For flexible parametric models "cmprsk" # For competing risks )) ``` -------------------------------- ### Install and Load survminer Source: https://github.com/kassambara/survminer/blob/master/_autodocs/index.md Install the survminer package from CRAN or GitHub and load it into your R session. ```r # From CRAN install.packages("survminer") # From GitHub (latest development version) devtools::install_github("kassambara/survminer") # Load package library("survminer") ``` -------------------------------- ### surv_fit with Matching Formulas and Datasets Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_fit.md Example of using surv_fit with multiple formulas and datasets, enabling matching between formulas and datasets using `match.fd = TRUE`. Requires setting a seed for reproducibility. ```r formulas <- list( Surv(time, status) ~ sex, Surv(time, status) ~ rx ) set.seed(123) sample1 <- dplyr::sample_frac(colon, 0.5) sample2 <- dplyr::sample_frac(colon, 0.5) datasets <- list(sample1 = sample1, sample2 = sample2) fit6 <- surv_fit(formulas, data = datasets, match.fd = TRUE) surv_pvalue(fit6) ``` -------------------------------- ### Inspecting Detailed Survival Estimates Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_summary.md This example shows how to use surv_summary to obtain detailed survival estimates and then inspect the first 10 rows of the resulting data frame. It also demonstrates how to extract the median survival statistics. ```r fit <- survfit(Surv(time, status) ~ sex, data = lung) res <- surv_summary(fit) # View detailed survival estimates head(res, 10) # View median survival attr(res, "table") ``` -------------------------------- ### Package Not Installed Solution Source: https://github.com/kassambara/survminer/blob/master/_autodocs/errors.md To resolve the 'package not installed' error, install the 'survminer' package from CRAN or GitHub, then verify the installation. ```r # Install from CRAN install.packages("survminer") ``` ```r # Or from GitHub devtools::install_github("kassambara/survminer") ``` ```r # Verify installation library("survminer") packageVersion("survminer") ``` -------------------------------- ### Missing Dependencies Solution Source: https://github.com/kassambara/survminer/blob/master/_autodocs/errors.md If a 'Namespace error' occurs due to missing dependencies, install all required packages, including 'ggplot2', 'ggpubr', 'survival', and others. ```r # Install missing dependencies install.packages(c("ggplot2", "ggpubr", "survival", "gridExtra", "broom", "dplyr", "tidyr", "purrr", "maxstat")) ``` -------------------------------- ### Install survminer from CRAN Source: https://github.com/kassambara/survminer/blob/master/README.md Use this command to install the survminer package from the Comprehensive R Archive Network (CRAN). ```r install.packages("survminer") ``` -------------------------------- ### Stratified Survival Analysis with surv_summary Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_summary.md This example demonstrates how to perform stratified survival analysis using surv_summary with multiple stratification variables. It shows how to subset the results to analyze survival for specific strata, such as males or individuals with a performance status of 0. ```r fit <- survfit(Surv(time, status) ~ sex + ph.ecog, data = lung) res <- surv_summary(fit) # Survival for males only males <- res[res$sex == "Male", ] # Survival for performance status 0 perf0 <- res[res$ph.ecog == 0, ] ``` -------------------------------- ### Fit Cox Model and Plot Deviance Residuals Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/cox-diagnostics.md This example demonstrates how to fit a Cox proportional hazards model using the `coxph` function and then visualize the deviance residuals using `ggcoxdiagnostics`. Ensure the `survival` and `survminer` libraries are loaded. ```r library("survival") library("survminer") fit <- coxph(Surv(time, status) ~ sex + log(inst) + log(nodes), data = cancer) # Deviance residuals ggcoxdiagnostics(fit, type = "deviance") ``` -------------------------------- ### Test Survival Models with Minimal Data Source: https://github.com/kassambara/survminer/blob/master/_autodocs/errors.md Verify your survival analysis setup by testing with built-in datasets like 'lung' and gradually adding complexity to the `ggsurvplot` function. ```r library("survival") # Test with simple case fit <- survfit(Surv(time, status) ~ sex, data = lung) ggsurvplot(fit, data = lung) # Should work ``` ```r # Add complexity gradually ggsurvplot(fit, data = lung, risk.table = TRUE) ggsurvplot(fit, data = lung, conf.int = TRUE) ``` -------------------------------- ### Get R Session Information Source: https://github.com/kassambara/survminer/blob/master/ISSUE_TEMPLATE.md Use this command to retrieve detailed information about your R session, including package versions. This is crucial for debugging. ```R # please paste here the result of devtools::session_info() ``` -------------------------------- ### Calculate Combined P-values for Multiple Survival Curve Comparisons Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_pvalue.md This example shows how to compute and combine p-values for multiple, independent survival curve comparisons. It takes a list of survfit objects and calculates p-values for each, displaying them together with an option to combine results. ```r fit1 <- survfit(Surv(time, status) ~ sex, data = lung) fit2 <- survfit(Surv(time, status) ~ ph.ecog, data = lung) fits <- list(sex = fit1, ecog = fit2) surv_pvalue(fits, combine = TRUE) # pval method pval.txt variable #1 0.001083102 survdiff p = 0.0011 sex #2 0.000000010 survdiff p < 0.0001 ph.ecog ``` -------------------------------- ### Custom Plotting with ggsurvplot_df Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_summary.md This example shows how to use the output of surv_summary with the ggsurvplot_df function to create custom survival plots, including confidence intervals and risk tables. ```r fit <- survfit(Surv(time, status) ~ sex, data = lung) res <- surv_summary(fit) # Use with ggsurvplot_df for custom plotting ggsubvplot_df(res, conf.int = TRUE, risk.table = TRUE) ``` -------------------------------- ### Check Functional Form with Partial Residuals Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/cox-diagnostics.md This example shows how to plot partial residuals against linear predictions to check the functional form of covariates in a Cox proportional hazards model using `ggcoxdiagnostics`. Ensure `survival` and `survminer` are loaded. ```r library("survival") library("survminer") fit <- coxph(Surv(time, status) ~ sex + log(inst) + log(nodes), data = cancer) # Check functional form ggcoxdiagnostics(fit, type = "partial", linear.predictions = TRUE) ``` -------------------------------- ### Basic surv_fit Usage Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_fit.md Demonstrates the basic usage of surv_fit, equivalent to survival::survfit, for a single formula and dataset. Requires the survival and survminer libraries. ```r library("survival") library("survminer") # Case 1: Basic usage - equivalent to survival::survfit fit1 <- surv_fit(Surv(time, status) ~ sex, data = colon) ggsurvplot(fit1, data = colon) ``` -------------------------------- ### Get survminer Citation Source: https://github.com/kassambara/survminer/blob/master/_autodocs/index.md Use this R command to retrieve the citation details for the survminer package, which should be included in any published work that utilizes the package. ```r citation("survminer") ``` -------------------------------- ### Configure General Table Parameters Source: https://github.com/kassambara/survminer/blob/master/_autodocs/configuration.md Set global parameters for all tables, such as height, color, font size, and font family. Options exist to color tables by strata or hide/color Y-axis labels. ```r # Height of all tables tables.height = 0.25 # Color all tables tables.col = "black" # Color tables by strata tables.col = "strata" # Font size for tables fontsize = 4 # Font family for tables font.family = "Courier New" # Hide table Y-axis labels tables.y.text = FALSE # Color table Y-axis labels tables.y.text.col = TRUE ``` -------------------------------- ### Create Cox Proportional Hazards Model Object Source: https://github.com/kassambara/survminer/blob/master/_autodocs/types.md Use this to create a coxph object, which is an input for Cox diagnostic and forest plot functions. Ensure the survival package is installed. ```r fit <- coxph(Surv(time, status) ~ sex + age, data = lung) class(fit) summary(fit) ``` -------------------------------- ### List of Formulas and List of Datasets (Cartesian Product) Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_fit.md Apply all formulas to all datasets, creating a Cartesian product. Returns a named list of survfit objects, named by formula and data set. ```r formulas <- list( sex = Surv(time, status) ~ sex, rx = Surv(time, status) ~ rx ) datasets <- list( colon = colon, lung = lung ) fit <- surv_fit(formulas, data = datasets) # Returns 4 survfit objects: sex_colon, sex_lung, rx_colon, rx_lung ``` -------------------------------- ### Enable Verbose Output with traceback and debug Source: https://github.com/kassambara/survminer/blob/master/_autodocs/errors.md Use `traceback()` within `tryCatch` to inspect function call stacks on error. Employ `debug()` to step through function execution for detailed analysis. ```r tryCatch( ggsurvplot(fit, data = data), error = function(e) traceback() ) ``` ```r debug(surv_summary) surv_summary(fit) # Step through function ``` -------------------------------- ### Customizing Adjusted Survival Curves Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/cox-forest-adjusted.md Provides an example of customizing the appearance of adjusted survival curves, including changing the color palette, applying a different theme, and modifying legend labels. ```r ggadjustedcurves(fit, variable = "sex", data = cancer, palette = c("#E7B800", "#2E9FDF"), ggtheme = theme_bw(), legend.labs = c("Male", "Female")) ``` -------------------------------- ### Fit and Visualize Survival Curves Source: https://github.com/kassambara/survminer/blob/master/NEWS.md Demonstrates how to fit survival curves using the survival package and visualize them with ggsurvplot, including p-value and confidence intervals. ```R require("survival") fit<- survfit(Surv(time, status) ~ sex, data = lung) # visualize require(survminer) ggsurvplot(fit, pval = TRUE, conf.int = TRUE, risk.table = TRUE) ``` -------------------------------- ### surv_fit with Multiple Formulas and Datasets Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_fit.md Demonstrates fitting survival curves using multiple formulas across multiple datasets. The output is a named list of survfit objects. ```r formulas <- list( by_sex = Surv(time, status) ~ sex, by_rx = Surv(time, status) ~ rx ) datasets <- list( colon = colon, lung = lung ) fit4 <- surv_fit(formulas, data = datasets) surv_pvalue(fit4) ``` -------------------------------- ### File Organization Structure Source: https://github.com/kassambara/survminer/blob/master/_autodocs/README.md Illustrates the directory structure of the survminer R package documentation, showing the organization of various markdown files for different aspects of the package. ```markdown /workspace/home/output/ ├── README.md # This file ├── index.md # Full overview and index ├── quick-reference.md # Task-oriented quick lookup ├── types.md # Type definitions ├── configuration.md # Theming and styling ├── errors.md # Errors and troubleshooting └── api-reference/ ├── ggsurvplot.md # Main plotting ├── surv_fit.md # Fit functions ├── surv_summary.md # Summary functions ├── surv_pvalue.md # Statistical tests ├── surv_cutpoint.md # Cutpoint analysis ├── cox-diagnostics.md # Cox diagnostics ├── cox-forest-adjusted.md # Cox visualization ├── utility-functions.md # Utilities └── plotting-variants.md # Specialized plots ``` -------------------------------- ### Access survminer Function Help Source: https://github.com/kassambara/survminer/blob/master/_autodocs/index.md These R commands allow you to access help documentation for specific survminer functions like ggsurvplot and surv_fit, or to browse all available functions and vignettes for the package. ```r # Function help ?ggsurvplot ?surv_fit # Browse all functions help(package = "survminer") # Vignettes vignette("survminer") browseVignettes("survminer") ``` -------------------------------- ### Customize Survival Plot Labels and Fonts Source: https://github.com/kassambara/survminer/blob/master/README.md Applies custom labels and font styles to survival curves, risk tables, and censor plots. This example demonstrates changing titles, subtitles, captions, and axis label fonts using the `labs` function and the `customize_labels` helper. ```r # Changing Labels # %%%%%%%%%%%%%%%%%%%%%%%%%% # Labels for Survival Curves (plot) ggsubr$plot <- ggsubr$plot + labs( title = "Survival curves", subtitle = "Based on Kaplan-Meier estimates", caption = "created with survminer" ) # Labels for Risk Table ggsubr$table <- ggsubr$table + labs( title = "Note the risk set sizes", subtitle = "and remember about censoring.", caption = "source code: website.com" ) # Labels for ncensor plot ggsubr$ncensor.plot <- ggsubr$ncensor.plot + labs( title = "Number of censorings", subtitle = "over the time.", caption = "source code: website.com" ) # Changing the font size, style and color # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # Applying the same font style to all the components of ggsubr: # survival curves, risk table and censor part ggsubr <- customize_labels( gggsubr, font.title = c(16, "bold", "darkblue"), font.subtitle = c(15, "bold.italic", "purple"), font.caption = c(14, "plain", "orange"), font.x = c(14, "bold.italic", "red"), font.y = c(14, "bold.italic", "darkred"), font.xtickslab = c(12, "plain", "darkgreen") ) ggsubr ``` -------------------------------- ### Basic surv_summary Usage Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_summary.md Demonstrates fitting a survival curve and then summarizing it using surv_summary. The output can be viewed with head() or printed entirely. Accessing attributes like 'table' provides median survival and other statistics. ```r library("survival") library("survminer") # Fit survival curves fit <- survfit(Surv(time, status) ~ rx + adhere, data = colon) # Summarize res <- surv_summary(fit, data = colon) # View the summary head(res) # Access summary information print(res) # Extract median survival and other statistics attr(res, "table") # Subset by strata res[res$strata == "rx=Lev", ] # Plot from summary (surv_summary output can be passed to ggsurvplot) ggsubvplot_df(res) # Simple stratification fit2 <- survfit(Surv(time, status) ~ sex, data = lung) res2 <- surv_summary(fit2) head(res2) # Multi-level stratification fit3 <- survfit(Surv(time, status) ~ sex + ph.ecog, data = lung) res3 <- surv_summary(fit3) head(res3) ``` -------------------------------- ### Configure Break and Limit Parameters for Axes Source: https://github.com/kassambara/survminer/blob/master/_autodocs/configuration.md Control axis breaks and limits for survival plots. You can break the time axis by a specific value or a vector of exact break points, break the y-axis, set x and y axis limits, and control whether axes start at the origin. ```r # Break time axis by value break.time.by = 100 # Or specify exact breaks break.time.by = c(0, 100, 200, 300) # Break Y-axis break.y.by = 0.1 break.y.by = c(0, 0.25, 0.5, 0.75, 1) # X-axis limits xlim = c(0, 500) # Y-axis limits ylim = c(0, 1) # Don't start axes at origin axes.offset = FALSE ``` -------------------------------- ### Comprehensive survminer Plot Customization Source: https://github.com/kassambara/survminer/blob/master/_autodocs/configuration.md An example demonstrating extensive customization of a survival plot using ggsurvplot. This includes setting titles, labels, colors, line types, confidence intervals, legend appearance, median survival lines, censoring marks, p-values, risk tables, axis scaling and breaks, themes, and font styles. ```r library("survival") library("survminer") fit <- survfit(Surv(time, status) ~ sex, data = lung) # Comprehensive customization ggsurvplot( fit, data = lung, # Title and labels title = "Lung Cancer Survival", xlab = "Time (months)", ylab = "Overall Survival", # Appearance palette = c("#E7B800", "#2E9FDF"), linetype = 1, size = 1, # Confidence intervals conf.int = TRUE, conf.int.fill = "lightblue", conf.int.alpha = 0.2, # Legend legend = c(0.8, 0.2), legend.title = "Gender", legend.labs = c("Male", "Female"), # Median survival surv.median.line = "hv", # Censoring marks censor = TRUE, censor.shape = "|", censor.size = 5, # P-value pval = TRUE, pval.size = 5, pval.coord = c(300, 0.9), # Risk table risk.table = TRUE, risk.table.title = "Subjects at Risk", risk.table.pos = "out", risk.table.col = "strata", risk.table.height = 0.2, tables.theme = theme_cleantable(), # Axes xlim = c(0, 600), ylim = c(0, 1), break.time.by = 100, xscale = "d_m", # Convert days to months # Theme ggtheme = theme_bw(), # Font customization font.title = c(14, "bold", "darkblue"), font.x = c(12, "bold", "black"), font.y = c(12, "bold", "black"), font.tickslab = c(10, "plain", "black") ) ``` -------------------------------- ### Project Directory Structure Source: https://github.com/kassambara/survminer/blob/master/_autodocs/MANIFEST.md This is the hierarchical structure of the survminer project, showing the organization of markdown files for documentation. ```bash /workspace/home/output/ ├── README.md # Entry point ├── index.md # Full reference ├── quick-reference.md # Task lookup ├── types.md # Type documentation ├── configuration.md # Styling reference ├── errors.md # Troubleshooting ├── MANIFEST.md # This file └── api-reference/ # Function documentation ├── ggsurvplot.md ├── surv_fit.md ├── surv_summary.md ├── surv_pvalue.md ├── surv_cutpoint.md ├── cox-diagnostics.md ├── cox-forest-adjusted.md ├── utility-functions.md └── plotting-variants.md ``` -------------------------------- ### Filtering Cutpoints by Statistical Significance Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_cutpoint.md This example shows how to filter cutpoints based on statistical significance. It first calculates cutpoints for multiple variables and then uses the `statistic` column from the summary to identify variables with a statistic greater than a specified threshold (e.g., 3.84 for a chi-square test with 1 degree of freedom), before categorizing the data using only these significant variables. ```r res.cut <- surv_cutpoint( myeloma, time = "time", event = "event", variables = c("DEPDC1", "WHSC1", "CRIM1") ) cutpoints <- summary(res.cut) # Use only significant cutpoints (e.g., p < 0.05) # Note: Significance is measured by the statistic, lower is better sig_vars <- rownames(cutpoints)[cutpoints$statistic > 3.84] # Chi-square threshold res.cat <- surv_categorize(res.cut, variables = sig_vars) ``` -------------------------------- ### Fit Cox Model and Create Forest Plot Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/cox-forest-adjusted.md Demonstrates fitting a Cox proportional hazards model using the 'survival' package and then generating a basic forest plot with 'survminer'. ```r library("survival") library("survminer") # Fit Cox model fit <- coxph(Surv(time, status) ~ sex + log(inst) + log(nodes) + extent + xray, data = cancer) # Create forest plot ggforest(fit, data = cancer) ``` -------------------------------- ### Multiple Test Methods for P-value Computation Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_pvalue.md Demonstrates how to compute p-values using different statistical tests like Gehan-Breslow, Tarone-Ware, and Peto-Peto by specifying the 'method' argument. Supports weight notation for methods. ```r # Fit survival curves fit <- survfit(Surv(time, status) ~ sex, data = colon) # Log-rank (default) surv_pvalue(fit, colon, method = "survdiff") # Gehan-Breslow (good for early differences) surv_pvalue(fit, colon, method = "n") # Tarone-Ware surv_pvalue(fit, colon, method = "sqrtN") # Peto-Peto surv_pvalue(fit, colon, method = "S1") # By weight notation surv_pvalue(fit, colon, method = "1") # Log-rank surv_pvalue(fit, colon, method = "n") # Gehan-Breslow ``` -------------------------------- ### Adjusting Minimal Proportion for Cutpoint Analysis Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_cutpoint.md Demonstrates how to adjust the `minprop` argument in `surv_cutpoint` to control the minimum proportion of observations in each group. A lower `minprop` allows for more flexibility, while a higher `minprop` imposes a stricter requirement. The output compares the cutpoints generated with different `minprop` values. ```r # Default: 10% minimum per group res.cut1 <- surv_cutpoint( myeloma, time = "time", event = "event", variables = c("DEPDC1"), minprop = 0.1 ) # More stringent: 20% minimum per group res.cut2 <- surv_cutpoint( myeloma, time = "time", event = "event", variables = c("DEPDC1"), minprop = 0.2 ) # Compare cutpoints print(summary(res.cut1)) print(summary(res.cut2)) ``` -------------------------------- ### Large-scale Gene Expression Analysis with surv_cutpoint Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_cutpoint.md This snippet shows how to load a dataset with multiple gene expression variables, find optimal cutpoints for all genes using `surv_cutpoint`, categorize genes based on these cutpoints using `surv_categorize`, fit survival curves for selected genes, and visualize them with `ggsurvplot`. It requires the `survminer` and `survival` libraries. ```r library("survminer") library("survival") # Load data with many genes data(myeloma) # Find optimal cutpoints for all genes gene_vars <- colnames(myeloma)[-(1:2)] # Exclude time and event columns res.cut <- surv_cutpoint( myeloma, time = "time", event = "event", variables = gene_vars, minprop = 0.1, progressbar = TRUE ) # Categorize all genes res.cat <- surv_categorize(res.cut) # Fit survival curves for each gene fit.list <- surv_fit( Surv(time, event) ~ DEPDC1 + WHSC1 + CRIM1 + FAM46C + FAM4C + FAM46D, data = res.cat ) # Visualize ggsubplot(fit.list, data = res.cat) ``` -------------------------------- ### Fit Cox Model and Plot Adjusted Curves Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/cox-forest-adjusted.md Demonstrates fitting a Cox proportional hazards model and then plotting adjusted survival curves for a specified variable using the 'average' method. Requires the survival and survminer libraries. ```r library("survival") library("survminer") # Fit Cox model fit <- coxph(Surv(time, status) ~ sex + log(inst) + log(nodes), data = cancer) # Adjusted curves for sex (adjusted for other covariates) ggadjustedcurves(fit, variable = "sex", data = cancer, method = "average") ``` -------------------------------- ### Group Survival Data by Variables Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/utility-functions.md Prepares survival data for grouped analysis by creating a list of datasets based on specified grouping variables. Requires the 'survival' and 'survminer' libraries. ```r library("survival") library("survminer") # Group by treatment and gender grouped.data <- surv_group_by(colon, grouping.vars = c("rx", "sex")) # Fit survival curves for each group fit <- surv_fit(Surv(time, status) ~ adhere, data = grouped.data) # Plot stratified by group variables ggsurvplot(fit, data = colon) ``` -------------------------------- ### Fit Complex Survival Curves and Visualize with Faceting Source: https://github.com/kassambara/survminer/blob/master/NEWS.md Demonstrates fitting a complex survival model using the survival package and visualizing the results with ggsurvplot, applying faceting by multiple factors. Requires 'survival' and 'survminer' packages. ```r require("survival") fit3 <- survfit( Surv(time, status) ~ sex + rx + adhere, data = colon ) # Visualize by faceting # Plots are survival curves by sex faceted by rx and adhere factors. require("survminer") ggsurv$plot +theme_bw() + facet_grid(rx ~ adhere) ``` -------------------------------- ### Exporting Survival Summary Data Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_summary.md This scenario demonstrates how to export the survival summary data generated by surv_summary to a CSV file. It also shows how to print the summary statistics table. ```r fit <- survfit(Surv(time, status) ~ sex, data = lung) res <- surv_summary(fit) # Write to CSV write.csv(res, file = "survival_summary.csv") # Summary statistics print(attr(res, "table")) ``` -------------------------------- ### Basic Cutpoint Determination with surv_cutpoint Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_cutpoint.md Find optimal cutpoints for multiple genes using the surv_cutpoint function. This requires loading the survminer library and a dataset like 'myeloma'. ```r library("survminer") data(myeloma) # Find optimal cutpoints for multiple genes res.cut <- surv_cutpoint( myeloma, time = "time", event = "event", variables = c("DEPDC1", "WHSC1", "CRIM1") ) # View summary of cutpoints summary(res.cut) # Print results print(res.cut) ``` -------------------------------- ### List of Formulas and Single Dataset Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_fit.md Apply multiple formulas to the same dataset. Returns a named list of survfit objects in the order of the formulas provided. ```r formulas <- list( sex = Surv(time, status) ~ sex, rx = Surv(time, status) ~ rx, adhere = Surv(time, status) ~ adhere ) fit <- surv_fit(formulas, data = colon) ``` -------------------------------- ### Define Survival Formula Syntax Source: https://github.com/kassambara/survminer/blob/master/_autodocs/types.md Shows standard R formula syntax for survival analysis, including basic survival formulas, Cox model formulas, and stratified analysis. ```r # Survival formula (left side) Surv(time, event) ~ group # Cox model formula Surv(time, event) ~ covariate1 + covariate2 # Stratified analysis Surv(time, event) ~ group + strata(institution) ``` -------------------------------- ### Grouped Data (group.by option) Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_fit.md Create separate fits for each variable combination using the group.by option. Returns a named list of survfit objects, grouped by strata. ```r fit <- surv_fit( Surv(time, status) ~ sex, data = colon, group.by = "rx" ) # Creates separate sex stratification for each rx level ``` -------------------------------- ### surv_fit for Grouped Analysis Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_fit.md Shows how to perform a grouped survival analysis using the `group.by` argument in surv_fit. This allows fitting curves for subgroups within a dataset. ```r fit5 <- surv_fit( Surv(time, status) ~ sex, data = colon, group.by = "rx" ) ggsurvplot(fit5, data = colon, facet.by = "rx") ``` -------------------------------- ### Load survminer library Source: https://github.com/kassambara/survminer/blob/master/README.md Load the survminer package into your R session to use its functions. ```r library("survminer") ``` -------------------------------- ### surv_fit with Multiple Formulas Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_fit.md Shows how to use surv_fit with a list of formulas applied to the same dataset. The function returns a named list of survfit objects. ```r formulas <- list( sex = Surv(time, status) ~ sex, rx = Surv(time, status) ~ rx, adhere = Surv(time, status) ~ adhere ) fits <- surv_fit(formulas, data = colon) ggsurvplot(fits, data = colon) surv_pvalue(fits) ``` -------------------------------- ### Configure Confidence Interval Display Source: https://github.com/kassambara/survminer/blob/master/_autodocs/configuration.md Control the visibility, style, fill color, and transparency of confidence intervals. Use 'conf.int.style' to choose between 'ribbon' and 'step'. ```r # Show confidence interval conf.int = TRUE # Confidence interval style: "ribbon" or "step" conf.int.style = "ribbon" # CI fill color conf.int.fill = "lightblue" # CI transparency (0 = transparent, 1 = opaque) conf.int.alpha = 0.15 ``` -------------------------------- ### Single Formula and Single Dataset Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_fit.md Use this for the simplest case, equivalent to standard survival::survfit(). Returns one survfit object. ```r fit <- surv_fit(Surv(time, status) ~ sex, data = colon) ``` -------------------------------- ### Fit survival curves Source: https://github.com/kassambara/survminer/blob/master/README.md Fit survival curves using the `survfit` function from the survival package. Requires the survival package to be loaded. ```r require("survival") fit <- survfit(Surv(time, status) ~ sex, data = lung) ``` -------------------------------- ### Single Formula and List of Datasets Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_fit.md Apply the same formula across multiple cohorts. Returns a named list of survfit objects in the order of the datasets provided. ```r fit <- surv_fit( Surv(time, status) ~ sex, data = list(colon = colon, lung = lung, breast = breast) ) ``` -------------------------------- ### Print survminer plots to ReporteRs PowerPoint Source: https://github.com/kassambara/survminer/blob/master/NEWS.md Demonstrates how to integrate survminer plots into a PowerPoint presentation using the ReporteRs package. Ensure 'newpage = FALSE' is used when printing the plot to avoid creating a new slide for each plot. ```r require(survival) require(ReporteRs) require(survminer) fit <- survfit(Surv(time, status) ~ rx + adhere, data =colon) survplot <- ggsurvplot(fit, pval = TRUE, break.time.by = 400, risk.table = TRUE, risk.table.col = "strata", risk.table.height = 0.5, # Useful when you have multiple groups palette = "Dark2") require(ReporteRs) doc = pptx(title = "Survival plots") doc = addSlide(doc, slide.layout = "Title and Content") doc = addTitle(doc, "First try") doc = addPlot(doc, function() print(survplot, newpage = FALSE), vector.graphic = TRUE) writeDoc(doc, "test.pptx") ``` -------------------------------- ### Formula-Data Matching Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_fit.md Apply formulas to matching data by position (formula[i] to data[i]) using match.fd = TRUE. Returns a named list of survfit objects. ```r formulas <- list( Surv(time, status) ~ sex, Surv(time, status) ~ rx ) datasets <- list( subset1 = dplyr::sample_frac(colon, 0.5), subset2 = dplyr::sample_frac(colon, 0.5) ) fit <- surv_fit(formulas, data = datasets, match.fd = TRUE) # formula[1] applied to datasets[1], formula[2] to datasets[2] ``` -------------------------------- ### Summarize Standard Kaplan-Meier Fit Source: https://github.com/kassambara/survminer/blob/master/_autodocs/api-reference/surv_summary.md Use this to summarize a standard Kaplan-Meier fit object created with survfit. Ensure the input is a valid survfit object. ```r fit <- survfit(Surv(time, status) ~ sex, data = lung) surv_summary(fit) ``` -------------------------------- ### Configure Risk Table in R Source: https://github.com/kassambara/survminer/blob/master/_autodocs/quick-reference.md Control the display and appearance of the risk table. Options include showing the table, its position, coloring by strata, and its height proportion. ```r risk.table = TRUE # Show table risk.table.pos = "out" # Outside plot risk.table.col = "strata" # Color by groups risk.table.height = 0.2 # Height proportion ``` -------------------------------- ### surv_cutpoint Parameters Source: https://github.com/kassambara/survminer/blob/master/_autodocs/quick-reference.md Identify optimal cut-points for survival analysis based on specified variables. Requires time and event columns. ```r surv_cutpoint( data, # dataset time = "time", # time column event = "event", # event column variables, # variable names minprop = 0.1 # min proportion ) ```