shiny分级菜单实现

2016/04/14

Categories: shiny Tags: data.frame data

本文主要目的实现R shiny中的分级菜单

选择地区A之后,再选择A地区的门店(下拉选项中只显示A地区门店)

实现效果

shiny分级菜单(shinydashboard界面)

代码

global.R

options(stringsAsFactors=FALSE, scipen=10, digits=4)

library(dplyr)

df_sample <- data.frame(region=rep(LETTERS[1:3], 4),
                        store=paste(rep(LETTERS[1:3], 4), 1:4, sep=""),
                        result=sample(1:100, 12))
region <- unique(df_sample$region)

ui.R

library(shiny)
library(shinydashboard)

shinyUI(
  dashboardPage(
    dashboardHeader(title = "分级菜单"),
    
    dashboardSidebar(
      sidebarMenu(
        selectInput("region", "地区:", 
                    choices = region),
        
        uiOutput("slt_store"),

        menuItem("分级菜单", tabName = "tab_budget", icon = icon("gear"))
      )
    ),
    
    
    dashboardBody(
      tabItems(
        tabItem(tabName = "tab_budget",
                fluidRow(
                  # 原始数据
                  box(h1("原始数据"),
                      tableOutput("df1")),
                  
                  # 筛选结果
                  box(h1("筛选结果"),
                      tableOutput("df2"))
                )
        )
      )
    )
  )
)

server.R

library(shiny)
library(shinydashboard)

shinyServer(function(input, output) {
  
  store_t <- reactive({
    df_sample %>%
      filter(region == input$region) %>%
      select(store)
  })
  # 在server.R中使用renderUI
  output$slt_store <- renderUI({
    selectInput("store", "门店:", choices = store_t()$store)
  })
  
  output$df1 <- renderTable({
    df_sample %>%
      arrange(region, store)
  })
  
   output$df2 <- renderTable({
     df_sample %>%
       filter(region == input$region) %>%
       filter(store == input$store)
  })
})

更新(2018-03-06):直接使用updateSelectInput即可