Search code examples
rcheckboxcheckboxlistshiny

Checkbox on table or dataframe


How do you select rows of data from a dataframe or table using checkboxes? I've done the following code but it seems the checkbox items are columns and does not really display the results.

Thanks for your help.

server.R

   shinyServer(function(input, output) {
       dataset<-reactive({
         data(cars)
         cars
       })

       output$choose_data <- renderUI({
         checkboxGroupInput("dtab", "Data Table", dataset()) 
    })

       dataset2<-reactive({
         input$dtab         
    })      

       output$data_table <- renderTable({
         data2()                    
       })
    })

ui.R

   shinyUI(pageWithSidebar(
         headerPanel(""),

         sidebarPanel(
         uiOutput("choose_data"),
         br()
         ),

        mainPanel(
        wellPanel("Data", tableOutput("data_table")
    ))))

Solution

  • Hi you can try package ReporteRs, there's a function FlexTable for creating html table (or word table), an example :

    library("shiny")
    library("ReporteRs")
    mymtcars <- head(mtcars)
    
    # ui
    ui <- fluidPage(
      tags$h1("Table with checkboxes"),
      tableOutput(outputId = "table"),
      br(),
      verbatimTextOutput(outputId = "out")
    )
    # server
    server <- function(input, output) {
      output$table <- renderFlexTable({
        # Create checkboxes
        mymtcars$Name <- paste0('<label><input type="checkbox" id="car', seq_along(rownames(mymtcars)), '"> <span>', rownames(mymtcars), '</span></label>')
        mymtcars <- mymtcars[c("Name", names(mtcars))] # Put col 'Name' in the first place
        ft <- vanilla.table(mymtcars) # convert to FlexTable objet
        ft[, "Name", to = "header"] <- parLeft() # left align checkboxes
        ft[, "Name"] <- parLeft() # left align header
        return(ft)
      })
      # the inputs created are in input$car1, input$car2, ...
      output$out <- renderPrint({
        # results
        res <- unlist(lapply(1:nrow(mymtcars), function(i) input[[paste0("car", i)]]))
        print(res)
        if (any(res)) {
          print(rownames(mymtcars)[res])
        }
      })
    }
    # launch app
    shinyApp(ui = ui, server = server)
    

    The result looks like :

    ft_example

    For more informations about FlexTable objects you can look here.