Reputation: 469
I am attempting to add the results of a Cox model to an R Shiny app. Unfortunately the results aren't printing out with the following line of code:
textOutput('modelSummary')
Also, I would like to add optional covariates via check-boxes. For example, I'm interested in adding something like the following below the last 'selectInput':
checkboxGroupInput("variable", "Covariates:",
c("Covariate 1" = "cov1",
"Covariate 2" = "cov2",
"Covariate 3" = "cov3"))
and then adding the selected variables to the Cox model.
The full Shiny App is below:
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(survival)
library(survminer)
library(ggplot2)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file","File input"),
selectInput("Survival",
label = "Length of Survival",
choices = c('survival1',
'survival2'),
selected = 'survival1'),
selectInput("Treatment",
"Treatment",
choices = c("treatment1", "treatmentt2"),
selected = "treatment1"),
selectInput("Endpoint",
"Endpoint",
choices = c("endpoint1", "endpoint2"),
selected = "endpoint1")
),
mainPanel(
plotOutput("KM"),
textOutput('modelSummary')
)
)
)
server <- function(input, output) {
options(shiny.maxRequestSize=40*1024^2)
raw_surv_data <- reactive({
req(input$file)
read.csv(input$file$datapath)
})
surv_data <- reactive({
raw_surv <- raw_surv_data()
data.frame(
Time = raw_surv[[input$Survival]],
Treatment = raw_surv[[input$Treatment]],
Endpoint = raw_surv[[input$Endpoint]]
)
})
surv_fit <- reactive({
survfit(Surv(Time , Endpoint) ~ Treatment, data = surv_data())
})
output$KM <- renderPlot({
ggsurvplot(surv_fit(), risk.table = TRUE, data = surv_data())
})
cox_fit <- reactive({
coxph(Surv(Time, Endpoint) ~ Treatment, data = surv_data())
})
output$modelSummary <- renderPrint({
summary(cox_fit)
})
}
shinyApp(ui = ui, server = server)
Upvotes: 0
Views: 399
Reputation: 84719
To add the covariates from the checkboxes, you can do:
cox_fit <- reactive({
model <- as.formula(paste0("Surv(Time, Endpoint) ~",
paste0(input$variable, collapse = "+")))
coxph(model, data = surv_data())
})
Upvotes: 1