Shiny - условная панель не распознает ввод - PullRequest
1 голос
/ 27 июня 2019

Я работаю с shiny, и у меня возникают трудности с распознаванием ввода R при использовании conditionalPanel.У меня есть две такие панели в моем приложении, потому что они нужны мне для создания определенного списка в зависимости от того, какую из переключателей выбирает пользователь.

Все отображается нормально с точки зрения пользовательского интерфейса, но по какой-то причине R не может подобрать какой-либо ввод, когда опция «Имя» пропускается через условную панель, даже если элемент введен в поле.Используется правильный список, но по какой-то причине он не обнаруживает никаких входных данных.Вот скриншот выборов и результатов.enter image description here

У меня нет проблем, если я выберу другую опцию из переключателей и введу элемент - он работает как положено.Вот код, с которым я работаю.

ui <- fluidPage(
         sidebarPanel(
             # the user can choose from two options within the radio buttons
             radioButtons("items_type", label = "Choose items for analysis"
                           , choices = list("Items - Item number & name" = "Both",  "Items - Item name only" = "Name")
                           , selected = "Both")
             # if the 'Both' option is selected, the items_list_names_id option is used
             , conditionalPanel(
                                condition = "output.items_type == 'Both'"
                               , selectInput("items", label = NULL, choices = items_list_names_id, multiple = TRUE))
            # if the 'Name' option is selected, the items_list_names option is used. input 
            # is not being detected here for some reason, and I'm wondering if it's because 
            # I use "items" for both selectInputs
            , conditionalPanel(
                                condition = "output.items_type == 'Name'"
                               , selectInput("items", label = NULL, choices = items_list_names, multiple = TRUE))

            # action button so the user can submit for analysis based on their selected options
            , actionButton("go", "Run", style = "color: white; background-color: #2759aa")
     )
  )



server <- function(input, output){

  # this portion is used to detect if the user alternates between either option from the radio buttons and uses the appropriate selectInput option
  output$items_type <- reactive({
     input$items_type
  })

  outputOptions(output, "items_type", suspendWhenHidden = FALSE)  

Results <- eventReactive(input$go, {

    # this portion is simply for testing for me to see how R recognizes the inputs
    observe({print(input$items_type)})
    observe({print(input$items)})

    # checks to make sure the user selects at least 1 item. For some reason,
    # this portion is triggered when at least 1 item is selected under the 'Name' 
    # condition from the conditional panel.
    validate(
        need(input$items > 0, 'Please select at least 1 item for analysis')
       ) 

#other steps start here, but the above is the more pertinent part
}

EDIT : Таким образом, похоже, что одинаковый идентификатор входа для обеих опций selectInput - это то, что заставляет R не распознавать ввод при переключении между условными панелями.Однако было бы идеально иметь один входной идентификатор, потому что intput$item используется в других частях моего кода, не показанных выше.Переписать код так, чтобы он использовал две переменные, например, input$item1 и input$item2, для каждого условия было бы потенциально очень проблематично.Я открыт для любых предложений, чтобы избежать этого.

РЕДАКТИРОВАТЬ 2 : Я подумал, может быть, использовать один conditonalPanel и использовать оператор switch для переключения между двумя списками в зависимости от выбора пользователя.Это должно работать теоретически и было бы удобным решением без изменения всего моего другого кода.Выглядит это так:

  , conditionalPanel(
    condition = "output.items_list_selection"
    , selectInput("items", label = 'Select items'
                  , choices = switch("output.items_list_selection", "Both" = items_list_names_id, "Name" = items_list_names)
                  , multiple = TRUE))

Но выпадающее меню не появляется, как это должно быть в этой ревизии.enter image description here

1 Ответ

1 голос
/ 27 июня 2019

Возможное решение - использовать updateSelectInput, поэтому нет проблем с двумя идентификаторами, имеющими одинаковый идентификатор ввода

library(shiny)

items_list_names_id = c("id1", "id2")
items_list_names = c('name1', 'name2')

ui <- fluidPage(
  sidebarPanel(
    # the user can choose from two options within the radio buttons
    radioButtons("items_type", label = "Choose items for analysis"
                 , choices = list("Items - Item number & name" = "Both",  "Items - Item name only" = "Name")
                 , selected = "Both"),
    # if the 'Both' option is selected, the items_list_names_id option is used
    selectInput("items", label = NULL, choices =  c('init'), multiple = TRUE),

    # action button so the user can submit for analysis based on their selected options
    actionButton("go", "Run", style = "color: white; background-color: #2759aa")
  )
)



server <- function(input, output, session){
  # change the choices depending on the value of input$intems_type
  observeEvent(input$items_type, {
    if(input$items_type == 'Both'){
      updateSelectInput(session, 'items', label = NULL, choices = items_list_names)
    }
    if(input$items_type == 'Name'){
      updateSelectInput(session, 'items', label = NULL, choices = items_list_names_id)
    }
  })

  # check if it's working
  observeEvent(input$go,{
    print(input$items)
    print(input$items_type)
  })

}

shinyApp(ui, server) 
...