How to update datatable after selecting data source from radio button?

192 Views Asked by At

I am preparing a shiny application. I have several data frames in which I store data about the population, broken down by years. So, for example, table_2017 stores data for 2017, table_2018 data for 2018, etc.

I would like to display all the data in a table and allow the user to choose the year that interests him. I thought that I would prepare a radio buttons and in this way the user will select which year he is interested in.

I tried to hide the source table name in the button id, then pass it to the datatable() function, unfortunately this method does not work because it is not recognized as a data frame and I get the message:

'data' must be 2-dimensional (e.g. data frame or matrix).

Hence my question: how can I update datatable after selecting data source from button radio? Maybe there are some ready-made tools for this (e.g. updatemenus for plotly)?

This is an example:

library(shiny)
library(DT)

ui <- fluidPage(
    
    radioButtons("years", "Choose year", inline = TRUE,
                 c("2017" = "table_2017",
                   "2018" = "table_2018",
                   "2019" = "table_2019")),
    DT::dataTableOutput("table")
       
)


server <- function(input, output) {
    
    a <- c("Region1","Region2","Region3","Region4")
    b <- c(100, 200, 300, 400)
    table_2017 <- data.frame(a,b)
    names(table_2017) <- c('Name', 'Population')
    
    c <- c("Region1","Region2","Region3","Region4")
    d <- c(500, 600, 700, 800)
    table_2018 <- data.frame(c,d)
    names(table_2018) <- c('Name', 'Population')
    
    e <- c("Region1","Region2","Region3","Region4")
    f <- c(900, 1000, 1100, 1200)
    table_2019 <- data.frame(e,f)
    names(table_2019) <- c('Name', 'Population')

    output$table <- DT::renderDataTable({
        
        data <- input$years
        datatable(data)
                        
        
    })
}


shinyApp(ui = ui, server = server)
1

There are 1 best solutions below

0
On BEST ANSWER

This is really simple, just add get(data))

The problem was that input$years from your radio buttons was just a character vector which is not executable by DT::datatable. With get(), you access the R environment and evaluate the dataframe, not the character vector in datatable.

Your table output is then

  output$table <- DT::renderDataTable({
    
    data <- input$years
    datatable(get(data))
    
    
  })

BTW, you should execute all static R code outside of your shiny app. Move your dataframes outside the server function or in a global.R file