在闪亮的应用程序中使用相同的 actionButton 在 plot 和 table 之间切换

Toggle between plot and table using the same actionButton in a shiny app

我有下面的 shiny 应用程序,我想使用相同的 actionButton().

在绘图(默认)和它的 table 之间切换
library(shiny)
library(DT)
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      
      
      actionButton("exc",
                   "Exchange")
    ),
    mainPanel(
      uiOutput(outputId = "car_plot")
      
    )
  )
)

server <- function(input, output) {
  showPlot <- reactiveVal(TRUE)

 
  
  observeEvent(input$exc, {
    showPlot(!showPlot())
  })
  
  output$car_plot <- renderUI({
    if (showPlot()){
      renderPlot({
        plot(mtcars)
      })
    }
    else{
      renderDataTable(
        datatable(
        mtcars)
      )
    }
  })
}

shinyApp(ui = ui, server = server)

我认为你所拥有的已经很接近了。我会为绘图和 table 创建单独的输出,如下所示(output$plotoutput$table),并根据 reactiveVal 的状态调用它们。让我知道这是否是您想要的行为。

server <- function(input, output) {
  
  showPlot <- reactiveVal(TRUE)
  
  observeEvent(input$exc, {
    showPlot(!showPlot())
  })
  
  output$car_plot <- renderUI({
    if (showPlot()){
      plotOutput("plot")
    }
    else{
      dataTableOutput("table")
    }
  })
  
  output$plot <- renderPlot({
    plot(mtcars)
  })
  
  output$table <- renderDataTable(datatable(mtcars))
  
}