two buttons, one plot - avoid reactiveValues

20 views
Skip to first unread message

mattek

unread,
Jan 6, 2017, 12:30:02 PM1/6/17
to Shiny - Web Framework for R
In the following code I have two buttons generating different datasets: vectors of random numbers from normal and Poisson distributions, respectively. I'm struggling with creating a reactive function that would assume a value of the outputs generated by either of the buttons. At the same time I'd like to avoid using reactiveValues.

After both buttons have been pressed, the plot is always that of the dataset generated by the 2nd button because the state of the buttons os not reset to 0. I guess I shouldn't be checking the state of the buttons this way but how can I make it work?

library(shiny)

ui <- shinyUI(fluidPage(
  titlePanel("2 buttons, 1 plot"),
  
  sidebarLayout(
    sidebarPanel(
      actionButton('inDataGen1', 'Generate dataset 1'),
      actionButton('inDataGen2', 'Generate dataset 2')
      ),
    mainPanel(plotOutput("plotHist", width = "100%"))
  )
))

server <- shinyServer(function(input, output, session) {

  # generate random dataset
  dataIn1 <- eventReactive(input$inDataGen1, {
    rnorm(1000)
  })
  
  dataIn2 <- eventReactive(input$inDataGen2, {
    rpois(1000, 2)
  })
  
  dataInBoth <- reactive({
    dm = NULL
    
    if (input$inDataGen1)
      dm = dataIn1()
    
    if (input$inDataGen2)
      dm = dataIn2()
    
    return(dm)
  })
    
  output$plotHist <- renderPlot({
    dm = dataInBoth()
    
    if (is.null(dm))
      return(NULL)
    else
      plot(hist(dm))
  })
})

shinyApp(ui = ui, server = server)


Reply all
Reply to author
Forward
0 new messages