Как предотвратить возврат updateSelectInput по умолчанию к первому значению?

#r #shiny #selectinput

#r #блестящий #selectinput

Вопрос:

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

 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] , но, похоже, это не помогает. Как я могу это исправить?

Комментарии:

1. Каким должно быть выбранное значение, если inpiut$maphealthcategory == 'Overdose rates and prescriptions' ?

2. @divibisan Это было бы «Частота назначения опиоидов» и input$maphealthyear было бы заполнено всеми значениями, отличными от 9999.