【问题标题】:Get the name in selectInput widget in R shiny在 R Shiny 中的 selectInput 小部件中获取名称
【发布时间】:2017-11-30 17:20:56
【问题描述】:

我正在使用带有选项组的闪亮包的 selectInput 函数Output of the selectInput function

在 ui.r 文件中我有类似的内容:

ListOfItemsWithNames = list(condition = c("KO","WT"),treatment = c("non","oui"))    
selectInput("Select1_contrast",label="Compare",ListOfItemsWithNames)

在 server.R 文件中,当我调用 input$Select1_contrast 时,我只得到选定的值(例如“oui”)。

有没有办法同时获取变量的值和名称(即“oui”和“治疗”)?

【问题讨论】:

    标签: html r shiny


    【解决方案1】:

    这是另一种可能性。它使用键值对。根据selectInput的文档,这些对是允许的

    选择可供选择的值列表。如果列表的元素被命名,则向用户显示该名称而不是值。这也可以是一个命名列表,其元素是(命名或未命名)列表或向量。如果是这种情况,最外面的名称将用作相应子列表中元素的“optgroup”标签。这允许您对类似的选择进行分组和标记。有关此功能的小演示,请参阅示例部分。

    addKeys = function(nested_list){
      keyed_nl = list()
      for (a in names(nested_list))
        for (b in (nested_list[[a]]))
          keyed_nl[[a]][[b]] = paste0(a, "-", b)
      keyed_nl
    }
    
    ListOfItemsWithNames = list(condition = c("KO", "WT"),
                                treatment = c("non", "oui"))  
    keyedList = addKeys(ListOfItemsWithNames)
    
    library(shiny)
    
    shinyApp(    
      fluidPage(
        selectInput("choiceKey", "choose", keyedList),
        textOutput('text')
      ),
      function(input, output, session)
        output$text = renderText(input$choiceKey)
    )
    

    如您所见,input$choiceKey 将为您提供类别和选项,并以- 分隔。使用strsplit,您可以分别获取这两个部分

    【讨论】:

      【解决方案2】:

      这应该可行。在这个版本中,您有第二个下拉菜单,因此还有第二个输入。

      library(shiny)
      
      ListOfItemsWithNames = list(condition = c("KO","WT"),treatment = c("non","oui"))  
      
      ui = inputPanel(
        selectInput("category", "choose a category", names(ListOfItemsWithNames )),
        selectInput("choice", "select a choice", ListOfItemsWithNames[[1]])
      )
      
      server = function(input, output, session){
        observe({
          updateSelectInput(session, "choice", 
            choices = ListOfItemsWithNames[[input$category]])
        })
      }
      
      shinyApp(ui, server)
      

      【讨论】:

      • 感谢您的回答,但我想避免添加新的 selectInput。我必须这样做很多次,所以我的想法是只使用一个 selectInput 来获取变量和选择的信息。
      猜你喜欢
      • 1970-01-01
      • 2020-10-13
      • 1970-01-01
      • 2017-05-08
      • 1970-01-01
      • 2021-03-24
      • 2019-03-04
      • 2020-09-14
      相关资源
      最近更新 更多