datanalyst
datanalyst

Reputation: 381

Use Shiny Action Button to Cycle Between 2 Tables

Issue:

I have a shiny dashboard where I display a table. In regard to a reproducible example, think of any basic table output. My table currently displays the absolute counts of certain metrics. I would like to press an action button that changes the view to a table that displays percentages.

My Question:

What is the appropriate syntax to use an action button to cycle between two different table outputs?

I'm curious if I can implement something along the lines of:

ui <- fluidPage(
  output$table,
  actionButton("do", "Click Me")
)

server <- function(input, output, session) {
  observeEvent(input$do, {
    table_1 # table 1 loads normally
    table_2 # table 2 loads upon button click
  })
}

Upvotes: 0

Views: 495

Answers (1)

AndS.
AndS.

Reputation: 8110

Here is an example on how to do this with mtcars.

library(shiny)
ibrary(tidyverse)
ui <- fluidPage(
    tableOutput("tbl"),
    actionButton("do", "Click Me")
)

server <- function(input, output, session) {
    vals <- reactiveValues(data = {
        mtcars %>% rownames_to_column() %>% select(rowname, mgp_exact = mpg) %>% head()
    })
    output$tbl <- renderTable({vals$data})
    observeEvent(input$do, {
        if(input$do %% 2 == 1){
            vals$data <- vals$data %>% mutate(mgp_exact = mgp_exact/max(mgp_exact)*100) %>% rename(mpg_pct = mgp_exact)
        }
        else{
            vals$data <- mtcars %>% rownames_to_column() %>% select(rowname, mgp_exact = mpg) %>% head()
        }
    })
}

shinyApp(ui, server)

I wrote it in so that the do button switches between percent and raw.

Upvotes: 1

Related Questions