如何修复 R Shiny 中的“错误:变量长度不同(为“input$s”找到)”

R. *_*tor 5 r shiny survival-analysis survival

我正在尝试制作一个简单的闪亮应用程序,用于创建卡普兰迈耶生存曲线,该曲线通过用户所做的选择进行分层。当我静态编码 KM 计算(使用列名称 thorTr)时,它可以工作,但计算和绘图是静态的。当我替换为 input$s 时,出现错误:变量长度不同(针对“input$s”找到)

我尝试查看其他使用 as.formula 和 Paste 的代码,但我不理解并且无法开始工作。但我是 R 和 Shiny 的新用户,所以也许我没有理解正确。这是一个类似的闪亮 ap,但我想使用 survminer 和 ggsurvplot 进行绘图

library(shiny)
library(ggplot2)
library(survival) 
library(survminer)

#load data
data(GBSG2, package = "TH.data")


#Define UI for application that plots stratified km curves
ui <- fluidPage(

  # Sidebar layout with a input and output definitions
  sidebarLayout(

    # Inputs
    sidebarPanel(

      # Select variable strat
      selectInput(inputId = "s", 
                  label = "Select Stratification Variable:",
                  choices = c("horTh","menostat","tgrade"), 
                  selected = "horTh")

    ),

    # Outputs
    mainPanel(
      plotOutput(outputId = "km")
    )
  )
)

# Define server function required to create the km plot
server <- function(input, output) {

  # Create the km plot object the plotOutput function is expecting
  output$km <- renderPlot({

    #calc KM estimate with a hard coded variables - the following line works but obviously is not reactive
    #km <- survfit(Surv(time,cens) ~ horTh,data=GBSG2)

    #replaced hard coded horTh selection with the respnse from the selection and I get an error
    km <- survfit(Surv(time,cens) ~ input$s ,data=GBSG2)

    #plot km
    ggsurvplot(km)

  })

}

# Create a Shiny app object
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

我希望有一个图可以根据用户的选择更新分层变量

Pau*_*aul 6

尝试使用surv_fit()而不是survfit().

surv_fit()是一个助手,与survminer相比,它的作用域不同survival:survit(),这似乎是您所需要的,正如拜伦所建议的那样。

我的片段如下所示:

output$plot <- renderPlot({

    formula_text <- paste0("Surv(OS, OS_CENSOR) ~ ", input$covariate)

    ## for ggsurvplot, use survminer::surv_fit instead of survival:survfit
    fit <- surv_fit(as.formula(formula_text), data=os_df)
    ggsurvplot(fit = fit, data=os_df)
})
Run Code Online (Sandbox Code Playgroud)


小智 3

两件事情:

  1. 调用中的公式survfit()需要明确定义。原始代码中传递给的对象survfit()使用函数右侧的字符值。这会引发一个错误,我们可以通过将整个粘贴的值转换为公式来解决该错误,即as.formula(paste('Surv(time,cens) ~',input$s))
  2. 需要在调用中定义公式ggsurvplot()以避免范围问题。这有点技术性,并且与编程方式有关ggsurvplot()。基本上,ggsurvplot()无法访问在其自己的调用之外定义的公式。

尝试更换

km <- survfit(Surv(time,cens) ~ input$s ,data=GBSG2)
ggsurvplot(km)
Run Code Online (Sandbox Code Playgroud)

ggsurvplot(survfit(as.formula(paste('Surv(time,cens) ~',input$s)),data=GBSG2))
Run Code Online (Sandbox Code Playgroud)