首页 > 解决方案 > 如何根据滑块输入选择过滤闪亮的日期(年份)?

问题描述

我正在使用 shiny 并且在我的 ui.R 文件中有一个 sliderInput() 和 selectInput() 。我希望根据用户对这两个字段的选择,在 hchart 函数中绘制所选数据。我非常接近解决问题,但是使用我的代码,它只是过滤年份的第一个数字和最后一个数字,而不是两者之间的所有内容。我尝试了 between 函数,但它没有用。

这是我的 ui.R 代码:

  tabItem(tabName = "crimetypesbyyear",

          fluidRow(

            box(
              title = "Date", 
              status = "primary", 
              solidHeader = TRUE,
              width = 6,
              sliderInput("ctypeDate", label = "Select Year", min = 2001, max = 2016, step = 1, sep = '', value = c(2001,2016))
            ),

            box(
              title = "Crime Type", 
              status = "primary", 
              solidHeader = TRUE,
              width = 6,
              height = 162,
              selectInput("ctypeCrimeType", label= "Select Crime Type", choices = unique(cc$Primary.Type)) 
            ),

            box(
              title = "Plot", 
              status = "danger", 
              solidHeader = TRUE,
              width = 12,
              highchartOutput(outputId = "ctypeOutput")
            ),

这是我的 server.R 代码:

output$ctypeOutput <- renderHighchart({

ctypeAnalysis <- cc[cc$Primary.Type == input$ctypeCrimeType,] %>% group_by(Year2) %>% summarise(Total = n()) %>% filter(Year2 %in% cbind(input$ctypeDate[1],input$ctypeDate[2]))

hchart(ctypeAnalysis %>% na.omit(), "column", hcaes(x = Year2, y = Total, color = Total)) %>%
hc_exporting(enabled = TRUE, filename = paste(input$ctypeCrimeType, "by_Year", sep = "_")) %>%
hc_title(text = paste("Crime Type by Year",input$ctypeCrimeType, sep = ": ")) %>%
hc_subtitle(text = "(2001 - 2016)") %>%
hc_xAxis(title = list(text = "Year")) %>%
hc_yAxis(title = list(text = "Crimes")) %>%
hc_colorAxis(stops = color_stops(n = 10, colors = c("#d98880", "#85c1e9", "#82e0aa"))) %>%
hc_add_theme(hc_theme_smpl()) %>%
hc_legend(enabled = FALSE)
})

所以这行代码应该更正:ctypeAnalysis <- cc[cc$Primary.Type == input$ctypeCrimeType,] %>% group_by(Year2) %>% summarise(Total = n()) %>% filter(Year2 %in% cbind(input$ctypeDate[1],input$ctypeDate[2]))有人知道吗?

标签: rhighchartsfiltershinyfiltering

解决方案


由于Year 2被格式化为一个因子,因此您需要将其转换回数值。您可以在与过滤功能相同的步骤中执行此操作,如下所示:

... filter(as.numeric(levels(Year2))[Year2] >= input$ctypeDate[1] & as.numeric(levels(Year2))[Year2] <= input$ctypeDate[2])

推荐阅读