如何使用Shiny:renderUI和Shiny:uioutput根据条件产生不同的输出类型

时间:2019-06-14 11:39:24

标签: r shiny

我希望能够根据先前选择的内容,与uiOutput产生不同的输出类型,如下所示:

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)

更简单的“选择”输出按预期工作,但上述返回的错误是: Warning: Error in switch: EXPR must be a length 1 vector [No stack trace available]

非常欢迎的解决方案。

最终我也希望对此进行模块化,因此执行此操作所涉及的任何其他挑战和解决方案也将很棒。

1 个答案:

答案 0 :(得分:1)

-1