首页 > 解决方案 > 如何在 actionButton 的执行中更新 R Shiny 中的 textOutput?

问题描述

我正在构建一个 R Shiny UI(拆分为 UI 和服务器),它花费大约三个小时来构建一个疾病临床记录的 data.frame,给定一些 Shiny UI 参数。完成后,data.frame 被传递给 Cox 模型,结果将显示为图。

在终端上运行 R 时,代码将在这三个小时内打印信息,例如,它已解析了多少患者/药物。

我曾尝试使用单独的 textOutput UI 功能,但似乎无法在单击按钮事件时执行的函数调用中更新 textOutput。我相信这可能与范围有关。我的代码由 UI 和服务器拆分:

注意:该按钮被单击一次,我希望看到 textOutput 在该单击时被更新几次,因为来自循环内的调用。

library(shiny)


shinyUI(fluidPage(

  # Application title
  titlePanel("CPRD EHR Statistical Toolset"),


  sidebarLayout(
    sidebarPanel(
      helpText("A long list of Input features below here."),
      mainPanel(
        h4("Medical record construction"),
        textOutput("numPatientsOutput"),
        actionButton("executeButton", "Execute Cox")
      )
    )
  )
))

library(shiny)

shinyServer(function(input, output) {

  observeEvent(input$executeButton, {
    coxDF<-runBuildModel(input, output)
  }) #endf of execute action

})

runBuildModel <- function(input, output) {
  for(i in 1:10) {
    #This is not updating.
    output$numPatientsOutput <- renderText({paste("patient:",i)})
  }
}

标签: rshiny

解决方案


基本上在server渲染之前运行所有代码。这就是为什么你只得到最后一行文本的原因。

您可以做的是reactiveValue在 for 循环中创建并更新此值。此外,您必须创建一个observer来跟踪该值。

工作示例

library(shiny)

ui <- shinyUI(fluidPage(

  # Application title
  titlePanel("CPRD EHR Statistical Toolset"),


  sidebarLayout(
    sidebarPanel(
      helpText("A long list of Input features below here.")),
    mainPanel(
      h4("Medical record construction"),
      htmlOutput("numPatientsOutput"),
      actionButton("executeButton", "Execute Cox")
    )

  )
))

server <- shinyServer(function(input, output) {
  runBuildModel <- function(input, output) {
    for(i in 1:10) {
      #This is not updating.
      rv$outputText = paste0(rv$outputText,"patient:",i,'<br>')
    }
  }

  rv <- reactiveValues(outputText = '')

  observeEvent(input$executeButton, {
    coxDF<-runBuildModel(input, output)
  }) #endf of execute action

  observe(output$numPatientsOutput <- renderText(HTML(rv$outputText)))
})



shinyApp(ui, server)

推荐阅读