In Shiny can a data frame be used as choices in se

2019-06-05 00:10发布

问题:

Is it possible for the choices in selectizeInput to be rows from a data frame? If so, would the returned data be a list of items from the selected row? I have been unable to make this work. In the code below, cityInput works since the choices are a character vector; but locationInput does not work, the item list in the select box is empty.

This is a common occurrence where user input requires selection based on the values in multiple columns to determine a unique row. In the example below, different cities have the same name and state is used to uniquely determine a location. Pasting the two columns together is one solution, but in complex cases this approach gets messy.

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)

回答1:

Apparently selectizeInput needs the columns of the data.frame to be called value and label.

Then it shows something for the locations:

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)