简体   繁体   中英

How to use shiny:renderUI and shiny:uioutput to produce different output types based on a condition

I would like to be able to produce a different output type from uiOutput based on an earlier selected, as in the following:

ui <- fluidPage(
  titlePanel("Dynamically generated user interface components"),
  fluidRow(
    selectInput("output_type",
      label = "Select type of output", 
      selected = "table",
      choices = c("table", "barplot", "graph") 
    ),
    uiOutput("diff_outputs")
    # textOutput("choice")
  )
)


server <- function(input, output){

  # output$choice <- renderText({
  #   switch(
  #     input$output_type,
  #     "table" = "you chose table",
  #     "barplot" = "you chose barplot",
  #     "graph" = "you chose graph"
  #   )
  #   
  # })
  get_choice <- reactive({input$choice})
  output$diff_outputs <- renderUI({
    if (is.null(input$output_type))
      return()

    switch(
      # input$output_type,
      get_choice(),
      "table" = renderTable({head(women)}),
      "barplot" = renderPlot({barplot(women$height)}),
      "graph"  = renderPlot({plot(women$height ~ women$weight)})
    )
  })
  # 
  output$output_type <- renderText({input$input_type})

}

shinyApp(ui = ui, server = server)

The simpler 'choice' output worked as expected, but the error returned by the above is: Warning: Error in switch: EXPR must be a length 1 vector [No stack trace available]

Solutions to this very welcome.

Eventually I would like to modularise this too, so any additional challenges and solutions involved in doing this would be great too.

ui <- fluidPage(
  titlePanel("Dynamically generated user interface components"),
  fluidRow(
    selectInput("output_type",
                label = "Select type of output", 
                selected = "table",
                choices = c("table", "barplot", "graph") 
    ),
    uiOutput("diff_outputs")
  )
)

server <- function(input, output){

  output$table <- renderTable({head(women)}) 

  output$barplot <- renderPlot({barplot(women$height)})

  output$scatterplot <- renderPlot({plot(women$height ~ women$weight)})

  output$diff_outputs <- renderUI({
    if (is.null(input$output_type))
      return()
    switch(
      input$output_type,
      "table" = tableOutput("table"),
      "barplot" = plotOutput("barplot"),
      "graph" = plotOutput("scatterplot")
    )
  })

}

shinyApp(ui = ui, server = server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM