@beginner2. The problem was interesting and strange. First, the resulting object of survfit
is a collection of informations for lazy evaluation. So, if you run it with a formula that evaluation needed like yours, it will save the expression only and evaluate later will raise error that object not found.
Second, the ggsurvplot
also cannot get final
from environment but it can get it from .GlobalEnv
. So, if you load it to .GlobalEnv
will work but load it in evaluation environment not work. You can pass final
into ggsurvplot
environment by argument data
will solve it. Hope I make myself clear. And this was an interesting question.
library(shiny)
library(shinyjs)
library(tidyverse)
library(survminer)
library(survival)
ui <- fluidPage(
titlePanel("survival"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "thegene", label = "Gene", choices = c("A1BG", "A1CF"), selected = "A1CF"),
radioButtons(inputId = "FileType", label = "Select the file type", choices = list("png", "pdf"), selected = "pdf"),
width = 3
),
mainPanel(
plotOutput("plot"),
downloadButton(outputId = "downloadPlot", label = "Download the plot"),
width = 9
)
)
)
server <- function(input, output, session) {
final <- read.csv("./final.csv")
genes <- as.factor(names(final[c(4:5)]))
env <- parent.frame()
vals <- reactiveValues()
alldat <- reactive({
choices <- genes
selected <- isolate(input$thegene)
if (!selected %in% choices) selected <- choices[1]
updateSelectInput(session, "thegene", choices = choices, selected = selected)
final
})
dat <- reactive({
x <- alldat()
x[ x$variable == input$thegene,,drop=FALSE]
})
output$plot <- renderPlot({
fit <- eval(parse(text = paste0("survfit(Surv(years, patient.vital_status) ~ ", input$thegene, ", data = final)")))
gg <-ggsurvplot(fit,
data = final,
pval = TRUE, conf.int = FALSE,
risk.table = TRUE, # Add risk table
risk.table.col = "strata", # Change risk table color by groups
linetype = "strata", # Change line type by groups
surv.median.line = "hv", # Specify median survival
ggtheme = theme_bw(), # Change ggplot2 theme
palette = c("#FF0027", "#060606"),
xlim = c(0,10),
break.x.by = 3,
xlab="Time in years",
risk.table.y.text.col = T, # colour risk table text annotations.
risk.table.y.text = FALSE)
vals$gg <- gg
print(gg)
})
output$downloadPlot <- downloadHandler(
filename = function() {
paste(input$thegene, input$FileType,sep=".")
},
# content is a function with argument file. content writes the plot to the device
content = function(file){
if(input$FileType=="png")
png(file, units="in", width=5, height=5, res=300)
else
pdf(file, width = 5, height = 5, onefile = FALSE)
print(vals$gg)
dev.off()
}
)
}
# Run the application
shinyApp(ui = ui, server = server)