【问题标题】:In Shiny can a data frame be used as choices in selectizeInput?在 Shiny 中,数据框可以用作 selectizeInput 中的选择吗?
【发布时间】:2018-12-02 16:20:57
【问题描述】:

selectizeInput 中的选项是否可以是数据框中的行?如果是这样,返回的数据是否会是所选行中的项目列表?我一直无法完成这项工作。在下面的代码中,cityInput 有效,因为选项是一个字符向量;但是locationInput不起作用,选择框中的项目列表是空的。

这是一种常见的情况,用户输入需要根据多列中的值进行选择以确定唯一的行。在下面的示例中,不同的城市具有相同的名称,并且使用州来唯一地确定位置。将两列粘贴在一起是一种解决方案,但在复杂的情况下,这种方法会变得混乱。

library(shiny)

locations <- data.frame(City=c("Ames", "Beaumont", "Beaumont", "Portland", "Portland"),
                        State=c("IA", "CA", "TX", "ME", "OR"))

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectizeInput("cityInput", "City", choices=NULL, selected=NULL),
      selectizeInput("locationInput", "Location", choices=NULL, selected=NULL)
    ),
    mainPanel("Main Panel")
  )
)

server <- function(input, output, session) {
  updateSelectizeInput(session, 'cityInput',
              choices = locations$City,
              server = TRUE
  )
  updateSelectizeInput(session, 'locationInput',
              choices = locations,
              server = TRUE
  )
}

shinyApp(ui, server)

【问题讨论】:

    标签: r shiny selectize.js


    【解决方案1】:

    显然selectizeInput 需要将data.frame 的列分别称为valuelabel

    然后它会显示一些位置:

    library(shiny)
    
    locations <- data.frame(value=c("Ames", "Beaumont", "Beaumont", "Portland", "Portland"),
                            label=c("IA", "CA", "TX", "ME", "OR"))
    
    
    ui <- fluidPage(
      sidebarLayout(
        sidebarPanel(
          selectizeInput("cityInput", "City", choices=NULL, selected=NULL),
          selectizeInput("locationInput", "Location", choices=NULL, selected=NULL)
        ),
        mainPanel("Main Panel")
      )
    )
    
    server <- function(input, output, session) {
    
      updateSelectizeInput(session, 'cityInput',
                           choices = locations$value,
                           server = TRUE
      )
      updateSelectizeInput(session, 'locationInput',
                           choices = locations,
                           server = TRUE
      )
    }
    
    shinyApp(ui, server)
    

    【讨论】:

    • 谢谢,但您的回答没有解决我的问题。通过在对 updateSelectizeInput 的两次调用中将选项设置为 locations$City 和 location$State,可以在原始代码中复制您的答案。事实上,它可以完全在客户端完成,方法是在对 selectizeInput 的调用中将选项设置为 locations$City 和 locations$State 并省去服务器端更新。我的目标是一个单一的选择框,每行有两列,城市和州。
    • 好的,我误解了你的问题。我只是用不同的方法编辑了我的答案。如您所见,当您将 data.frame 添加到选项时,选项将为空,因为它不知道要访问什么。
    • 可能是这样,但令人费解的是,该文档另有说明 [shiny.rstudio.com/articles/selectize.html].具体来说,服务器端选择部分说“这里的数据可以是任意的 R 数据对象,例如(命名的)字符向量或数据框。”
    • 刚刚编辑了我的答案。我发现了一些有用的东西here。 colnames 必须是 value / label
    猜你喜欢
    • 2019-07-31
    • 2019-05-20
    • 1970-01-01
    • 2021-06-10
    • 2018-07-19
    • 2018-04-03
    • 2021-01-08
    • 1970-01-01
    • 2017-12-29
    相关资源
    最近更新 更多