Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling clicks of multiple actionButtons in a shiny app

Tags:

r

shiny

If I have multiple dynamically generated actionButtons in my shiny app, is there a way to know which actionButton was clicked and perform some computation with the Id of the button clicked?

like image 423
jpmarindiaz Avatar asked Nov 10 '22 05:11

jpmarindiaz


1 Answers

I had a similar problem, although the buttons are not dynamically generated in my case. It is not clear from the question if the emphasis is on the "dynamically generated" aspect. If so my answer does not help you much...

To simplify my answer i reduce the problem to the following:

  • I have two actionButtons in my UI (id="increase" and id="decrease") and i have an integer variable (var) and text output (id="actual_value") to show the actual value. One of the buttons should increase the value by one the other should decrease it and obviously the output should show the updated value.

The solution is:

    shinyServer(function(input, output, session) {
         increase <- reactive({
            if( input$increase == 0 ) return(  )
            var <- var + 1
          })

          decrease <- reactive({
            if( input$decrease  == 0 ) return(  )
            var <- var - 1
          })

          actual.value <- reactive({
            increase()
            decrease()
            var
          })

          output$actual_value <- renderText({
            paste("Actual value is: ", actual.value() )
          })
    })

So the explanation is that there are two reactive inputs (i.e., the buttons), and two corresponding reactive expressions (increase and decrease). A third reactive expression (actual.value) depends on the first two and returns the actual value of var. The reactive output depends on this.

So you create two separate reactive expressions for the two buttons (increase and decrease) and then multiplex them in the third one (actual.value).

This works, however i do not know if this is the best approach to solve such a problem.

like image 99
novaczkisz Avatar answered Nov 15 '22 06:11

novaczkisz