Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify a Shiny reactive expression with two forms of user input

I want to use a reactive expression that can be updated in either of two ways. Below is a very simple example with either numeric input or a reset button to set the expression back to its original state (in practice the expression is more complex, so can't use reactive values). It seems that only the second definition of num is recognised, so in the example the numeric input is ignored).
What am I missing?
Many thanks!

ui <- fluidPage(
  numericInput("number", "Input", 1),
  actionButton("button", "Reset"),
  textOutput("check")
)
server <- function(input, output){
  num <- reactive({
    input$number
  })
  num <- eventReactive(input$button, {
    1
  })
  output$check <- renderText({
    num()
  })
}
shinyApp(ui, server)
like image 532
Marcus Avatar asked Sep 02 '25 06:09

Marcus


1 Answers

Edit:

We can use observeEvent() with each input to update num().

library(shiny)

ui <- fluidPage(
  numericInput("number", "Input", 1),
  actionButton("button", "Reset"),
  textOutput("check")
)
server <- function(input, output) {
  num <- reactiveVal()

  observeEvent(input$number, {
    num(input$number)
  })

  observeEvent(input$button, {
    num(1)
  })

  observeEvent(c(input$button, input$number), {
    output$check <- renderText({
      num()
    })
  })
}
shinyApp(ui, server)
like image 108
jpdugo17 Avatar answered Sep 05 '25 01:09

jpdugo17