albert
albert

Reputation: 325

Use "withProgress" in shiny

I'm trying to understand how "Progress indicators" works in shiny, so I created a loop (fictional) that takes about 7seconds (1.8GHz) to run. I would like to show a progress bar after user clicks a button Go!

This is the code:

    ui <- fluidPage(
  headerPanel("Progress indicators"),
  sidebarPanel(
    numericInput("n", "N:", min = 0, max = 100, value = 50000),
    br(),
    actionButton("goButton", "Go!")

  ),
  mainPanel(
    verbatimTextOutput("nText")
  )
)

server <- function(input, output) {

  fictional <-  reactive({
  n=input$n
  p = rep(0,n)
  for(j in 1:n){
      data1=rnorm(1000,1,2)
      data2=runif(1000,1,2)
      p[j] =  min(data1,data2)
     }
    pw1 =  mean(p)
    return(pw1)
})
  ntext <- eventReactive(input$goButton, { fictional()})

  output$nText <- eventReactive(input$goButton, {

    withProgress(message = 'Progress indicators', {
    ntext()
     })
  })
}
shinyApp(ui, server)

I was trying to use withProgress but I don't know how to use it to wrap the codes because when I click in Go! it show me the progress bar but stops. Disappears when the loop ends

Any suggestions?

Thank you in advance!

Upvotes: 4

Views: 5519

Answers (1)

lukeA
lukeA

Reputation: 54247

See ?withProgress- you have to tell your progess bar the progress, e.g.

   ui <- fluidPage(
  headerPanel("Progress indicators"),
  sidebarPanel(
    numericInput("n", "N:", min = 0, max = 100, value = 50000),
    br(),
    actionButton("goButton", "Go!")

  ),
  mainPanel(
    verbatimTextOutput("nText")
  )
)

server <- function(input, output) {

  fictional <-  reactive({
  n=input$n
  p = rep(0,n)
  for(j in 1:n){
      if (j%%100==0) incProgress(100/n)
      data1=rnorm(1000,1,2)
      data2=runif(1000,1,2)
      p[j] =  min(data1,data2)
     }
    pw1 =  mean(p)
    return(pw1)
})
  ntext <- eventReactive(input$goButton, { fictional()})

  output$nText <- eventReactive(input$goButton, {

    withProgress(message = 'Progress indicators', {
    ntext()
     })
  })
}
shinyApp(ui, server)

Upvotes: 3

Related Questions