Search code examples
rdrop-down-menudatatablesshinydashboard

problem with selecting variables/columns using radioButtons and selectInput in Shiny


I'm unable to select/unselect different columns of mtcars dataset using both radioButtons and selectInput function in Shiny. Can someone please help me out as i'm stuck on it since last 2 days. I shall be extremely grateful.

Regards

data(mtcars)
#Ui
ui <- fluidPage(
sidebarLayout( 
 sidebarPanel(
  column(width = 10,
         radioButtons(inputId="variables", label="Select variables:",
                      choices = c("All","mpg","cyl","disp"),
                      selected = "All", inline = TRUE )),

  column(width = 10,
         selectInput(inputId = "level", label = "Choose Variables to 
                     display", multiple = TRUE, choices =  names(mtcars)[4:11]))),


mainPanel ( 
  h2("mtcars Dashboard"),
  DT::dataTableOutput("table"))))


#server
server<-function(input, output) {

output$table <- DT::renderDataTable(DT::datatable(filter='top', editable = TRUE, caption = 'mtcars',
                                                {  

                                    data <- mtcars
                                    data<-data[,input$variables,drop=FALSE]

                                      column = names(mtcars)
                                      if (!is.null(input$level)) {
                                          column = input$level  }

                                       data

                                                })) }
shinyApp(ui = ui, server = server)

Solution

  • library(shiny)
    library(DT)
    data(mtcars)
    #Ui
    ui <- fluidPage(
    sidebarLayout( 
      sidebarPanel(
          column(width = 10,
          radioButtons(inputId="variables", label="Select variables:",
          choices = c("All","mpg","cyl","disp"),
          selected = "All", inline = TRUE )),
          column(width = 10,
          selectInput(inputId = "level", label = "Choose Variables to 
          display", multiple = TRUE, choices =  names(mtcars)[4:11]))),
          mainPanel ( 
          h2("mtcars Dashboard"),
          DT::dataTableOutput("table"))
      ))
    
    #server
    server<-function(input, output, session) {
      data <- mtcars
      tbl <- reactive({
        if(input$variables=='All'){
          data
        }else{
          data[,c(input$variables,input$level),drop=FALSE]
        }
      })
    output$table <- DT::renderDataTable(DT::datatable(filter='top', caption='mtcars', tbl()))  
    }
    shinyApp(ui = ui, server = server)
    

    Here is what I understand from your requirements, I hope it what you are looking for. Always try to avoid calculations inside render*.