R Shiny: Create dynamic bucket lists UI output

Viewed 222

I am trying to create a for loop for the following code that would dynamically iterate multiple bucket lists dependent on prior inputs e.g from example_Table. Please see the following:

library(shiny)
# install.packages("sortable")
library(sortable)

example_Table = cbind(c(1,2,3,4),c("a","b","c","d"))

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

server <- function(input, output, session) {
  
  
  output$Dyanmic_Bucket <- renderUI({
    bucket_list(
      header = "",
      group_name = "Dyanmic_Bucket",
      orientation = "horizontal",
      add_rank_list(
        text = example_Table[1,1],
        labels =  example_Table[1,2]
      ),
      add_rank_list(
        text = example_Table[2,1],
        labels =  example_Table[2,2]
      ),
      add_rank_list(
        text = example_Table[3,1],
        labels =  example_Table[3,2]
      ),
      add_rank_list(
        text = example_Table[4,1],
        labels =  example_Table[4,2]
      )
      )
})
  
}

shinyApp(ui, server)

How could this be created without manually creating each add_rank_list? I have attempted to create a for loop, but I am clearly off the mark with the following:

for (i in 1:nrow(example_Table)){
  add_rank_list(
    text = example_Table[i,1],
    labels =  example_Table[i,2]
  )
}

Many thanks for your help.

1 Answers

This could be achieved using do.call and lapply like so:

library(shiny)
library(sortable)

example_Table = cbind(c(1,2,3,4),c("a","b","c","d"))

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

server <- function(input, output, session) {
  
  rank_list_items <- lapply(seq(nrow(example_Table)), function(x) {
    add_rank_list(
      text = example_Table[x,1],
      labels =  example_Table[x,2]
    )
  })
  
  output$Dyanmic_Bucket <- renderUI({
    do.call("bucket_list", args = c(
      list(header = "",
           group_name = "Dyanmic_Bucket",
           orientation = "horizontal"),
      rank_list_items
    ))
  })
  
}

shinyApp(ui, server) 
Related