r - 如何修复 R Shiny 中的 'Error: variable lengths differ (found for ' input$s')'

标签 r shiny survival-analysis survival

我正在尝试制作一个简单的 Shiny ap 来创建 kaplan-meier 生存曲线,这些曲线通过用户所做的选择进行分层。当我对 KM 计算进行静态编码(使用列名 thorTr)时,它可以工作,但计算和绘图是静态的。当我用 input$s 替换时,我得到 ERROR:variable lengths different (found for 'input$s')

我试过查看其他使用 as.formula 和粘贴的代码,但我不明白并且无法开始工作。但我是 R 和 Shiny 的新用户,所以也许我没有做对。这是一个类似的 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)

我希望有一个图来更新用户选择的分层变量

最佳答案

两件事情:

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

  • 尝试更换
    km <- survfit(Surv(time,cens) ~ input$s ,data=GBSG2)
    ggsurvplot(km)
    


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

    关于r - 如何修复 R Shiny 中的 'Error: variable lengths differ (found for ' input$s')',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54058769/

    相关文章:

    r - Shiny 的应用程序下载按钮和 future_promise : Error in enc2utf8: argument is not a character vector

    r - 使用 R 中的 RMS 包预测生存?

    r - 将XY点添加到由levelplot生成的栅格 map 中

    r - 映射两个列表

    R Shiny 的 react 表,渲染图无法工作

    r - 在网站上部署和在R中部署时,错误消息不同

    r - 在 R 中向 ggsurvplot 添加一条垂直直线

    r - 由生存包中的 survfit 函数生成的生存曲线

    list - R 中的多级列表

    r - 如何导出每个键的数据表?