首页 > 解决方案 > 在 Shiny 中,数据框可以用作 selectizeInput 中的选择吗?

问题描述

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)

标签: rshinyselectize.js

解决方案


显然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)

推荐阅读