Dynamic repeating conditionalPanel in R shiny dashboard

寵の児 提交于 2021-02-07 10:01:59

问题


I am trying to create a dynamic conditional panel. So my conditions are as follows:

Input in UI:

selectInput('inpt','Input Number', seq(1,50,1), selectize = FALSE)

My conditional panel UI input is:

conditionalPanel(
  "input.inpt == 2",
  box(
   selectInput("id1", "Select number",
               seq(1, 24, 1), selected = 1),
   selectInput("id2", "Select number",
               seq(1, 24, 1), selected = 1),
   width = 2,
   status = "primary"
  )
 ),

conditionalPanel(
  "input.inpt == 3",
  box(
    selectInput("id1", "Select number",
                seq(1, 24, 1), selected = 1),
    selectInput("id2", "Select number",
                seq(1, 24, 1), selected = 1),
    selectInput("id3", "Select number",
                seq(1, 24, 1), selected = 1),
    width = 2,
    status = "primary"
  )

So this code is working great! But the problem is it is hardcoded.

As you can check in selectInput, I have total of 50 inputs.

I have the exactly same number of new selectInput panels depending on the input.

Example: If 3 is selected, I will have 3 selectInput with id1, id2, id3 (as shown in code above). If 18 is selected, I will have 18 selectInput with id1, id2, ..., id18. If 'n' is selected, I will have 'n' selectInput with id1, id2,... idn.

I don't want to write this code so many times.

P.S.: All changes are made in just box(). I don't want to create multiple boxes.

So how to generalised this? If I have 'n' number of inputs how to repeat this approach?


回答1:


You could use a renderUI rather than a conditionalPanel:

output$selectors <- renderUI({
  n <- input$inpt
  selectors <- lapply(1:n, function(i){
    selectInput(paste0("id",i), "Select number", seq(1,24), selected = 1)
  })
  do.call(function(...){
    box(..., width = 2, status = "primary")
  }, selectors)
})

and uiOutput("selectors") in your Shiny UI.


Small example:

library(shiny)
library(shinydashboard)

ui <- fluidPage(
  br(),
  selectInput("inpt", "Input Number", seq(1,50), selectize = FALSE),
  br(),
  uiOutput("selectors")
)

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

  output[["selectors"]] <- renderUI({
    n <- input[["inpt"]]
    selectors <- lapply(1:n, function(i){
      selectInput(paste0("id",i), "Select number", seq(1,24), selected = 1)
    })
    do.call(function(...){
      box(..., width = 2, status = "primary")
    }, selectors)
  })

}

shinyApp(ui, server)


来源:https://stackoverflow.com/questions/60117104/dynamic-repeating-conditionalpanel-in-r-shiny-dashboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!