R Shiny:备用表格数据和绘图可视化

R Shiny: alternate tabular data and plot visualization

请看一下 reprex 中的简单 Shiny 应用程序。 我的想法(我正在努力通过一些 switch 语句来完成它)是能够使用侧边栏中的按钮 select 仅显示 table 或仅显示线图。

有人知道如何实现吗?

library(shiny)
library(shinyWidgets)
library(tidyverse)
library(DT)
#> 
#> Attaching package: 'DT'
#> The following objects are masked from 'package:shiny':
#> 
#>     dataTableOutput, renderDataTable



df <- tibble(x=seq(20), y=seq(20))


ui <- fluidPage(
     sidebarLayout(
         sidebarPanel(

                         pickerInput("viz_type","Select what you want to see",
                        choices=(c("Tabular Data", "Line Plot")),
                        selected="Tabular Data",
                        options = list(`actions-box` = TRUE,
                                       `selected-text-format` = "count > 3"),multiple = F)

         ),

         mainPanel(

    plotOutput("myplot" ,
               ) ,
    DTOutput("table")

             
)
         ))






server <- function(input, output) {

    compound_data <- reactive({
        df
        })

    output$table <- renderDT(compound_data())

    myplot <- reactive({

df1 <- compound_data()

gpl1 <- df1 %>%
    ggplot(aes(x = x, y = y)) +
    geom_point()
    


gpl1

})

    output$myplot <- renderPlot({
        myplot()
        
    })

    
    }




shinyApp(ui = ui, server = server)
#> PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.
静态 R Markdown 文档不支持闪亮的应用程序

reprex package (v2.0.1)

于 2021-09-15 创建

您可以在ui中添加conditionalPanel。当满足条件时,面板内的每个小部件、table、绘图或文本都会显示。

在您的情况下,当输入 $viz_type 为“线图”时显示绘图,当输入 $viz_type 等于“表格数据”时显示 table。

代码

library(shiny)
library(shinyWidgets)
library(tidyverse)
library(DT)

df <- tibble(x=seq(20), y=seq(20))


ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      
      pickerInput("viz_type","Select what you want to see",
                  choices=(c("Tabular Data", "Line Plot")),
                  selected="Tabular Data",
                  options = list(`actions-box` = TRUE,
                                 `selected-text-format` = "count > 3"),multiple = F)
      
    ),
    
    mainPanel(
      
    # Added conditions for showing Line Plot or Table
      conditionalPanel(
        condition = "input.viz_type == 'Line Plot' ",
        plotOutput("myplot")
      ),
      conditionalPanel(
        condition = "input.viz_type == 'Tabular Data' ",
        DTOutput("table")
      )
      
    )
  ))






server <- function(input, output) {
  
  compound_data <- reactive({
    df
  })
  
  output$table <- renderDT(compound_data())
  
  myplot <- reactive({
    
    df1 <- compound_data()
    
    gpl1 <- df1 %>%
      ggplot(aes(x = x, y = y)) +
      geom_point()
    
    
    
    gpl1
    
  })
  
  output$myplot <- renderPlot({
    myplot()
    
  })
  
  
}




shinyApp(ui = ui, server = server)

例子