简体   繁体   中英

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)

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM