r - 如何在 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)})
}
}
解决方案
基本上在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)
推荐阅读
- c# - 如何在 SWIG 中将 C 参数(const uint8_t*,unsigned int 大小)转换为 C# byte[]
- php - 为什么 Laravel Dusk 不启动浏览器窗口?
- python - load_weights_from_hdf5_group original_keras_version AttributeError:“str”对象没有属性“decode”
- c# - 在 EF Core 中的 SaveChanges() 上获取所有错误
- java - Jgit - 如何过滤大文件克隆
- django - Django 组和模型实例
- java - 如何使用 ItextPDF 5.0 创建带页码的多页目录
- docker - Azure Pipeline Angular Build Docker Image 失败
- redux - 当 Redux 状态更改时,React 组件表不会重新渲染
- python - 如何根据 django 中的相同键值将列表转换为 json