vendredi 31 juillet 2020

Rshiny: Extract checked values from a list of grouped checkboxes

I'm trying to make check boxes for each car model in a grouping variable, 'cylinders'.

To achieve this, I'm using lapply() to go through the groups making a groupedCheckbox in a collapsing well panel, for each.

However only some of the checked car models are read. Initially all of the checked cars in the first cylinder group can be read but not those in the second two groups !

However once some of the car models in the first group are ticked, then cars in the second two groups are also read. Image of multiple checkbox groups with only checkboxes in first box are read

MultipleGroupCheckboxProblem

Does anyone know how all of the ticked cars can be extracted into a reactive vector?

I have a feeling the solution might involve proper use of lapply and/or unlist.

Also the car names originate from the row names of the input table.

Code here, using mtcars :

library(shiny)
library(shinyBS)
ui <- fixedPage(
  h2("R Shiny: Multiple collapsing tickboxes"),
  

  
  tags$style(HTML("
.checkbox{margin-top: -20px; margin-left: 0px; margin-bottom: -5px;padding:-5px; margin-right: -400px;}
  .panel{margin: -5px;}")),

  uiOutput("grouped.tickboxes"), 
  
  textOutput("selectedtext")
)

# .panel{margin: 2px;padding:1px}")),



server <- function(input, output, session) {
  
  output$grouped.tickboxes <- renderUI({
    
    lapply(sort(unique(mtcars$cyl)), function(x) {
      
      fluidRow(
        
        div(tags$style(HTML("
                 .checkbox{margin: 0px; ;padding:0px; margin-right: -400px;}")),
            
        bsCollapsePanel(paste0("Cylinders: ", x), 
                        style = "color:grey; border-top: 1px solid black",
                        # style = "color:grey;",
                        
                        column(12,
                               
                               checkboxGroupInput(inputId = "stuff", 
                                                  NULL, choices = sort(row.names(subset(mtcars, cyl %in% x))))))
      )
      )
    })
  })
  
  
  seltex = reactive({
    ## maybe need to use lapply to read values.
    # paste0(input$stuff, collapse = ", ")
    # paste0(as.vector(unlist(input$stuff, use.names = FALSE)), collapse = ", ")
    # as.vector(unlist(input$stuff, use.names = FALSE))[1]
    # head(str(input$stuff))
    # lapply(input$stuff, str(input$stuff)[2]
    # paste0(unlist(unlist(unlist(input$stuff), use.names = FALSE)), collapse = ", ")
    # paste0(unlist(unlist(unlist(input$stuff)), use.names = FALSE), collapse = ", ")
    # paste0(unlist(unlist(input$stuff)), collapse = ", ")
    paste0("Selected cars : ", paste0(unlist(input$stuff), collapse = ", "))
  })

  output$selectedtext = renderText({ as.character(seltex() )})
  
}


# grouped.tickboxes

shinyApp(ui, server)



Aucun commentaire:

Enregistrer un commentaire