8

I would like an output data table after selection of some simple criteria, once an action button is clicked.

The code works without the action button as an input. As soon as I include the observeEvent function, the result is no longer generated. See example code below.

Note: Removing the line observeEvent(input$gobutton,{ and the corresponding }) will produce the correct output.

library(shiny)

ui <- fluidPage(
  fluidRow(column(6,div(checkboxGroupInput("test1", "Testing buttons", 
                                           choices=c("A","B","C"),
                                           selected=c("A","B","C"))))),

  hr(),

  actionButton("gobutton","Start"),

  dataTableOutput("summary_table")

)

server <- function(input,output){

  output$summary_table <- renderDataTable({

    observeEvent(input$gobutton,{

    df=data.frame(col1=input$test1,col2=seq(1,length(input$test1),1))

    df
    })
  })
}

shinyApp(ui=ui, server=server)
sym246
  • 1,836
  • 3
  • 24
  • 50

1 Answers1

14

Wrap it in a eventReactive instead:

library(shiny)

ui <- fluidPage(
  fluidRow(column(6,div(checkboxGroupInput("test1", "Testing buttons", 
                                           choices=c("A","B","C"),
                                           selected=c("A","B","C"))))),

  hr(),
  actionButton("gobutton","Start"),
  dataTableOutput("summary_table")

)

server <- function(input,output){

  data <- eventReactive(input$gobutton,{
    if(is.null(input$test1)){
      return()
    }

    df <- data.frame(col1=input$test1,col2=seq(1,length(input$test1),1))
    df
  })

  output$summary_table <- renderDataTable({
    data()
  })
}

shinyApp(ui=ui, server=server)
Pork Chop
  • 28,528
  • 5
  • 63
  • 77
  • Works perfectly. Thank you. Do you have any idea why `observeEvent` doesn't work, but `eventReactive` does? – sym246 Oct 02 '17 at 07:31
  • 10
    An observer is like a reactive expression in that it can read reactive values and call reactive expressions, and will automatically re-execute when those dependencies change. But unlike reactive expressions, it `doesn't yield a result` and can't be used as an input to other reactive expressions. Thus, observers are only useful for their side effects (for example, performing I/O). https://shiny.rstudio.com/reference/shiny/latest/observe.html – Pork Chop Oct 02 '17 at 07:33