Как предотвратить использование updateSelectInput по умолчанию первого значения? - PullRequest
0 голосов
/ 04 марта 2019

В настоящее время у меня есть три входа, которые все зависят друг от друга.Каждый последующий вход обновляется на основе значения предыдущего выбора.Код для этого следующий:

library(dplyr)
library(shiny)

    metric <- c('Opioid prescribing rate', 'Opioid prescribing rate','Opioid prescribing rate','Opioid prescribing rate','Opioid prescribing rate', 'Opioid prescribing rate',
              'Opioid prescribing rate','Opioid prescribing rate','Opioid prescribing rate','Opioid prescribing rate','Opioid prescribing rate','Rate of new cancers',
              'Rate of cancer deaths', 'Arthritis prevalence', 'Percent of population over 65', 'Percentage of civilian non-institutionalized population ages 18-64 with a disability',
              'Median household income')
  year <- c(2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,9999,9999,9999,9999,9999,9999)
  year_range <- c('','','','','','','','','','','','2011-2015','2011-2015','2015','2010','2010','2013-2015')
  category <- c('Overdose rates and prescriptions','Overdose rates and prescriptions','Overdose rates and prescriptions','Overdose rates and prescriptions',
                'Overdose rates and prescriptions','Overdose rates and prescriptions','Overdose rates and prescriptions','Overdose rates and prescriptions',
                'Overdose rates and prescriptions','Overdose rates and prescriptions','Overdose rates and prescriptions','Miscellaneous health metrics and diseases',
                'Miscellaneous health metrics and diseases','Miscellaneous health metrics and diseases','Socioeconomic','Socioeconomic','Socioeconomic')

  healthmapyeardata <- as.data.frame(cbind(metric, year, year_range, category))

  ui <- fluidPage(selectInput("maphealthcategory", "Category:", c("Overdose rates and prescriptions",
                                                                   "Miscellaneous health metrics and diseases",
                                                                   "Socioeconomic"), selected = "Overdose rates and prescriptions"),
                  selectInput("maphealthmetric", "Metric:", c("")),

                  conditionalPanel("output.healthmetrics", selectInput("maphealthyear", "Year:", choices = c("All years" = ""))),

                  conditionalPanel("output.healthmetrics === false", htmlOutput("healthmapyearrange"))
                  )

  server <- function(input, output, session) {
    observe({
      metrics <- filter(healthmapyeardata, category %in% input$maphealthcategory) %>%
        `$`('metric') %>%
        unique() %>%
        sort()

      updateSelectInput(session,
                        "maphealthmetric",
                        choices = metrics,
                        selected = metrics[1])

      years <- if (is.null(input$maphealthmetric))
        character(0)
      else {
        filter(healthmapyeardata, metric %in% input$maphealthmetric) %>%
          `$`('year') %>%
          unique() %>%
          sort()
      }

      updateSelectInput(session,
                        "maphealthyear",
                        choices = years,
                        selected = years[1])
    })

    output$healthmetrics <- reactive({
      metrics <- as.list(healthmapyeardata %>% filter(year != 9999) %>% select(metric) %>% unique())
      input$maphealthmetric %in% metrics
    })

    # COPY - if chosen metric only has aggregated data, then this text will render
    period <- reactive({as.character(healthmapyeardata %>% filter(metric == input$maphealthmetric) %>% select(year_range))})

    output$healthmapyearrange <- renderUI({
      HTML(paste0("Time period: ", period()))
    })
    outputOptions(output, "healthmetrics", suspendWhenHidden = FALSE)
  }

  shinyApp(ui = ui, server = server)

В соответствии с этим кодом, если я выберу «Прочие показатели здоровья и заболевания» в качестве категории, мой input$maphealthmetric должен быть заполнен c('Percent of population over 65', 'Percentage of civilian non-institutionalized population ages 18-64 with a disability',Median household income') и должен иметьВыбран «средний доход домохозяйства».Это работает как надо.Однако каждый раз, когда я пытаюсь выбрать другое значение input$maphealthmetric, оно автоматически сбрасывается на «Средний доход домохозяйства».Я также пытался удалить строку selected = metrics[1], но это не помогло.Как я могу это исправить?

...