在闪亮的应用程序中使用相同的 actionButton 在绘图和表格之间切换

时间:2021-04-18 22:27:50

标签: r shiny dt

我有下面的 shiny 应用程序,我想使用相同的 actionButton() 在绘图(默认)和它的表格之间切换。

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)

1 个答案:

答案 0 :(得分:1)

我认为你所拥有的很接近。我将为绘图和表格创建单独的输出,如下所示(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))
  
}