您可以看到我正在尝试设置三个不同的过滤器,它们都相互反应,但是当我测试它时,它总是给我错误。
我要完成的工作就是以说我选择“地区1”的方式来设置这些过滤器,它会仅给我相应的州(俄亥俄州)和城市(哥伦布和克利夫兰) )。同时,假设我同时选择了区域1和4,它将为我提供各州(俄亥俄州和密歇根州)和城市(哥伦布,克利夫兰和大瀑布城,但没有底特律)。同时,假设我想忽略“领域”字段并决定直接进入“州”过滤器,它将为我提供所有州选项(请记住,我尚未选择任何领域)。如果我只是想直接进入城市过滤器,那也是一样。
因此,基本上,我希望所有过滤器相互反应联系在一起,但又没有严格的层次结构,因此我必须先选择地区,然后再选择州,最后再选择城市。
我能很好地解释吗?
这是代码。
设置:
library(shiny)
library(dplyr)
library(highcharter)
df <- structure(list(territory = structure(c(1L,1L,2L,3L,4L
),.Label = c("1","2","3","4"),class = "factor"),state = structure(c(3L,2L),.Label = c("Indiana","Michigan","Ohio"
),city = structure(c(2L,6L,4L,5L),.Label = c("Cleveland","Columbus","Detroit","Gary","Grand Rapids","Indianapolis"),sales = 5:10,leads = 11:16),class = "data.frame",row.names = c(NA,-6L)) %>%
mutate_all(as.character)
ui <- {
fluidPage(
fluidRow(
selectizeInput(
inputId = 'selectTerritory',label = 'Select Territory',choices = c('All Territories',sort(unique(df$territory))),multiple = TRUE,selected = 'All Territories'),uiOutput(
outputId = 'selectState'),uiOutput(
outputId = 'selectCity'),highchartOutput("test")
# plotOutput()
)
)
}
server <- function(input,output,session) {
output$selectState <- renderUI({
# if 'All Territories' is not selected,then filter df by selected Territories. Otherwise,just get all states.
if (!('All Territories' %in% input$selectTerritory)) {
df <- df %>%
filter(
territory %in% input$selectTerritory)
}
states <- sort(unique(df$state))
selectizeInput(
inputId = 'selectState',label = 'Select State',choices = c('All States',states),selected = 'All States')
})
output$selectCity <- renderUI({
# same strategy
if (!('All States' %in% input$selectState)) {
df <- df %>%
filter(
state %in% input$selectState,territory %in% input$selectTerritory)
} else {
df <- df %>%
filter(
territory %in% input$selectTerritory)
}
cities <- sort(unique(df$city))
selectizeInput(
inputId = 'selectCity',label = 'Select City',choices = c('All Cities',cities),selected = 'All Cities')
})
geog <- reactive({
res <- df %>% filter(is.null(input$selectTerritory) | territory %in% input$selectTerritory,is.null(input$selectState) | state %in% input$selectState,is.null(input$selectCity) | city %in% input$selectCity)
})
output$test <- renderHighchart({
res <- geog() %>% select_all()
graph <- res %>% group_by_all() %>% summarise(totals=sum(sales))
highchart() %>% hc_add_series(data = graph,type = "bar",hcaes(y = totals),showInLegend = TRUE) %>% hc_add_theme(hc_theme_flat())
})
}
shinyApp(ui,server)