Raja
Raja

Reputation: 167

Recursive change in reactive table in shiny

The following code is a simpler version of my original problem. The code should do the following steps sequentially:

  1. The table will show entire 'mtcars'
  2. On each click on Half button, it should show half of the previous data
  3. On each click on One3 button, it should show one third of the previous data

** Can someone tell me how to use reactiveValues etc. to solve the problem?

library(shiny)
library(DT)
ui <- fluidPage(tabsetPanel(
  tabPanel("Table",
           actionButton("Half","Click for Half"),
           actionButton("One3","Click for One Third"),
           DTOutput("tbl")
  )
))

server = function(input, output, session){
  data <- reactiveValues(
    tbl = mtcars
  )

  tbl <- eventReactive(T,data$tbl)

  observeEvent(input$Half,{
    data$tbl <- data$tbl[1:(round(nrow(data$tbl)/2)),]
    tbl <- eventReactive(input$Half,data$tbl)
      })

  observeEvent(input$One3,{
    data$tbl <- data$tbl[1:(round(nrow(data$tbl)/3)),]
    tbl <- eventReactive(input$One3,data$tbl)
  })


  output$tbl <- renderDT(tbl())

}

shinyApp(ui = ui, server = server)

Upvotes: 1

Views: 246

Answers (1)

A. Suliman
A. Suliman

Reputation: 13125

No need for eventreactive as reactiveValues(tbl = mtcars) default value i.e. mtcars will be there presented at output$tbl until the user hits Half then it will be updated automatically in the reactive chain.

server = function(input, output, session){
    data <- reactiveValues(tbl = mtcars)

    observeEvent(input$Half,{
      data$tbl <- data$tbl[1:(round(nrow(data$tbl)/2)),]
    })

    output$tbl <- renderDT(data$tbl)

  }

Upvotes: 1

Related Questions