Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-reactive scope in Shiny

In my Shiny App, there are two inputs: the number of observations (an integer), and the color (a character to be choosen between red, green and blue). There is also a "GO!" action button.

Which Shiny function to use in order to:

  • have the random numbers regenerated and the histogram updated with this new data only when the user click on the "Go!" button.
  • be able to change the color of the histogram on the fly without regenerating the random numbers.

I would prefer a solution that provides the maximum clarity to the code.

See below one of my unsuccessful tentative with isolate.

# DO NOT WORK AS EXPECTED

# Define the UI
ui <- fluidPage(
  sliderInput("obs", "Number of observations", 0, 1000, 500),
  selectInput('color', 'Histogram color', c('red', 'blue', 'green')),
  actionButton("goButton", "Go!"),
  plotOutput("distPlot")
)

# Code for the server
server <- function(input, output) {
  output$distPlot <- renderPlot({
    # Take a dependency on input$goButton
    input$goButton

    # Use isolate() to avoid dependency on input$obs
    data <- isolate(rnorm(input$obs))
    return(hist(data, col=input$color))
  })
}

# launch the App
library(shiny)
shinyApp(ui, server)
like image 736
tic-toc-choc Avatar asked Dec 13 '25 13:12

tic-toc-choc


1 Answers

Something like this? It will only update the data() variable upon button click. You can read up on the observeEvent and eventReactive here

#rm(list = ls())
# launch the App
library(shiny)
ui <- fluidPage(
  sliderInput("obs", "Number of observations", 0, 1000, 500),
  selectInput('color', 'Histogram color', c('red', 'blue', 'green')),
  actionButton("goButton", "Go!"),
  plotOutput("distPlot")
)

# Code for the server
server <- function(input, output) {
  data <- eventReactive(input$goButton,{
    rnorm(input$obs)
  })
  
  output$distPlot <- renderPlot({
    return(hist(data(), col=input$color))
  })
}
shinyApp(ui, server)

enter image description here

like image 124
Pork Chop Avatar answered Dec 15 '25 13:12

Pork Chop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!