【问题标题】:Set an Output Component to Empty in R/Shiny在 R/Shiny 中将输出组件设置为空
【发布时间】:2021-12-11 11:53:47
【问题描述】:

我的 Shiny 主面板中有 uiOutput 和 plotOutput 组件。

plotOutput("plot_data"), 
uiOutput("summary_data")

我在服务器函数中有典型的代码来响应和填充每个组件,例如:

  output$plot_data <- renderPlot({
    hist(data_vars())
    })
    
  output$summary_data <- renderPrint({
    summary(data_vars())
    }) 

我想为每个添加功能,将另一个的输出组件设置为 NULL 或空字符串等,以便这两个输出共享相同的空间。当一个有数据时,另一个是空的。我不认为它会以这种方式工作,但它可能看起来像这样:

  output$plot_data <- renderPlot({
    # Code to "flatten" uiOutput

    # Then populate the component    
    hist(data_vars())
    })
    
  output$summary_data <- renderPrint({
    # Code to "flatten" plotOutput
    
    # Then populate the component
    summary(data_vars())
    }) 

我认为这可以使用 observeEvent 来完成,但我还没有找到一种方法来完全删除其中的内容,以便另一个可以占用页面上的相同空间。请帮忙。谢谢。

【问题讨论】:

    标签: r user-interface shiny server


    【解决方案1】:

    您可以只拥有一个uiOutput,而不是单独的plotOutputprintOutput,然后您可以在服务器中添加代码以显示您希望在该插槽中的哪个输出。这是一个工作示例,我在其中添加了一个按钮以在视图之间切换。

    library(shiny)
    
    ui <- fluidPage(
      actionButton("swap","Swap"),
      uiOutput("showPart")
    )
    
    server <- function(input, output, session) {
      showState <- reactiveVal(TRUE)
      observeEvent(input$swap, {showState(!showState())})
      
      output$plot_data <- renderPlot({
        hist(mtcars$mpg)
      })
      
      output$summary_data <- renderPrint({
        summary(mtcars)
      })
    
      output$showPart <- renderUI({
        if (showState()) {
          plotOutput("plot_data")
        } else {
          verbatimTextOutput("summary_data")    
        }
      })
    }
    
    shinyApp(ui, server)
    

    使用此方法,只有两个输出中的一个会在 uiOutput 槽中呈现。

    【讨论】:

    • 谢谢!我想你搞定了。我仍然需要弄清楚如何以你的例子来更新 output$plot_data 和 output$summary_data ,比如 mtcars 发生变化。我想我可以使用 reactive() 函数来做到这一点。
    猜你喜欢
    • 2021-07-25
    • 2021-06-17
    • 2017-06-02
    • 2018-09-30
    • 2020-03-19
    • 2016-04-11
    • 2021-01-25
    • 2021-05-18
    • 2022-01-19
    相关资源
    最近更新 更多