Search code examples
cssrshinyshinywidgets

R Shiny dynamic CSS within checkboxGroupButtons


I am unable to dynamically alter the status of checkboxGroupButtons. Please see the following, where the choices alter dynamically, but the status only renders as the final variable within the for loop (in this case 3 is printed repeatedly, as opposed to 1,2,3).

library(shiny)
library(shinyWidgets)

example = cbind(c("a", "b", "c"), c(1, 2, 3))

ui <- fluidPage(uiOutput("example_output"))

server <- function(input, output, session) {
  output$example_output = renderUI({
    example_output = c()
    for (i in 1:nrow(example)) {
      example_output[[i]] = tagList()
      example_output[[i]] = checkboxGroupButtons(paste0("id_", i), choices = {
        print(example[i, 1])
        example[i, 1]
      },
      status = {
        print(i)
        example[i, 2]
      })
    }
    example_output
  })
}

shinyApp(ui, server)

How can I alter the status dynamically?

Thank you.


Solution

  • You can use lapply as shown below.

    library(shiny)
    library(shinyWidgets)
    
    example = cbind(c("a", "b", "c"), c(1, 2, 3))
    
    ui <- fluidPage(uiOutput("example_output"))
    
    server <- function(input, output, session) {
      output$example_output = renderUI({    
        tagList(
          lapply(1:nrow(example), function(i){
            checkboxGroupButtons(paste0("id_", i), choices = {
              print(example[i, 1])
              example[i, 1]
            },
            status = {
              print(i)
              example[i, 2]
            })
          })
        )
        
      })
    }
    
    shinyApp(ui, server)