【问题标题】:R Shiny Two Outputs for One Action ButtonR 一个操作按钮的闪亮两个输出
【发布时间】:2019-07-15 12:15:09
【问题描述】:

我正在尝试使用 R Shiny 中的操作按钮来启动运行缓慢的 JAGS 模型。我希望在用户第一次点击按钮时出现一些文本,显示他们按下按钮的时间,以便他们知道正在发生一些事情。

到目前为止,操作按钮正在工作,但它会等到慢速运行的模型完成后才显示模型输出和文本。

我查看了以下问题,但它们似乎没有回答我的问题,至少不是以我理解的方式: R Shiny execute order Pattern for triggering a series of Shiny actions

我是 Shiny 的新手,所以我希望这是一个简单的问题。

Run.me <- function(a){
# some fake slow function
# This actually takes about 8 hours in real life 

for (i in 2:a) {
Foo[i] <<- Foo[i-1] + sample(1:20,1)
}}

library(shiny)

定义服务器逻辑----

server <- function(input, output) {

observeEvent(input$runmodel, {
output$model.running <- renderText({paste("Model started at", Sys.time())})
})

observeEvent(input$runmodel, {
Foo <<- rep(1, 1e6)
Run.me(1e6)
output$model.ran <- renderTable({head(Foo)})
})

}

定义用户界面----

ui <- fluidPage(

fluidRow(
column(5, align = "center",
       actionButton("runmodel", "Run the Model")),
textOutput("model.running")
),


fluidRow(
column(5, align = "center", tableOutput("model.ran"))
)
)

运行应用程序----

shinyApp(ui = ui, server = server)

【问题讨论】:

  • 是您想要文本以便他们知道正在发生的事情的唯一原因吗?您可以考虑在加载时使用微调器。例如,我使用包shinycssloaders
  • 您能否使用 shinycssloaders 发布答案并解释它们的工作原理?
  • @Megan 这是我的主要原因,但我也希望人们知道自从他们开始这个过程以来已经过去了多少时间。稍后我可能会添加一个“杀死”按钮,所以最好有一个允许一些灵活性的选项。
  • 现在我已经添加了以下消息,当按下按钮时它会消失。不如添加文本那么好,但仍然表明正在发生某些事情。 output$model.running
  • 这是有道理的。 @AdamWaring 我会添加它以防其他人使用它

标签: r shiny shiny-reactivity


【解决方案1】:

一个可能性,如果我正确理解了这个问题:

server <- function(input, output) {

  observeEvent(input$runmodel, {
    Foo <<- rep(1, 1e6)
    Run.me(1e6)
    output$modelran <- renderTable({head(Foo)})
  })

}

js <- "
$(document).ready(function() {
  $('#runmodel').on('click', function(){
    var date = new Date().toLocaleString();
    $('#busy').html('Model started: ' + date);
  });
  $('#modelran').on('shiny:value', function(event) {
    $('#busy').html('');
  });
});
"

ui <- fluidPage(
  tags$head(
    tags$script(HTML(js))
  ),

  fluidRow(
    column(5, align = "center",
           actionButton("runmodel", "Run the Model")),
    tags$p(id = "busy")
  ),
  fluidRow(
    column(5, align = "center", tableOutput("modelran"))
  )

)

【讨论】:

  • 这太完美了! “标签”的使用是我从未想过的。
【解决方案2】:

在我也在缓慢构建模型的应用程序中,我在服务器中使用了一个进度条。我知道这并不完全符合您的要求,但您可能会发现这是一个可以接受的解决方案。

modeloutput= reactive(withProgress(message = 'Generating JAGs model', value = 0, {
    incProgress(50); generate_jags(params)
}))

output$jags = renderPlot(modeloutput())

我也会关注这个问题的答案,因为我也更喜欢在输出将出现的实际绘图窗口中具有消息或加载栏的解决方案。

我还找到了另一种解决方案,该解决方案通过在单击操作按钮后将其屏蔽,并具有一个小的加载栏和完成消息。可在此处获得:

https://github.com/daattali/advanced-shiny/tree/master/busy-indicator

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2018-03-13
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    相关资源
    最近更新 更多