如何使用来自服务器的信息填充闪亮的输入选项

How to populate input options for shiny using information from server

我在闪亮的应用程序上使用过滤器来过滤数据框。目前,我必须手动将可能的值输入 ui 。有没有办法从服务器数据框中读取唯一值并使用该列表填充输入选项?我知道可以通过使 table 全局化来做到这一点,但我试图避免这样做。

示例代码:

ui <- fluidPage(
  sidebarPanel(
    selectInput(inputId = 'col1Input',
                label ='col1',
                choices = c(1,2,3))),
  mainPanel(
    DT::dataTableOutput("table")))
server <- function(input,output){
  df <- data.frame('col1' = c(1,2,3), 'col2' = c(1,2,3))
  output$table <- DT::renderDataTable(dplyr::filter(df, col1 == input$col1Input))
}

shinyApp(ui = ui, server = server)

谢谢!

您可以使用 renderUI 从服务器构建 UI。然后,您可以简单地使用服务器中数据框中的其中一列来构建 select 输入?

See here 了解如何使用 renderUI.

ui <- fluidPage(
  uiOutput("sidebarOutput"),
  uiOutput("mainPanel")
)

server <- function(input,output){
  df <- data.frame('col1' = c(1,2,3), 'col2' = c(1,2,3))
  output$sidebarOutput <- renderUI({
    sidebarPanel(
      selectInput(inputId = 'col1Input',
                  label =colnames(df[1]),
                  choices = df[[1]]))
  })

  output$mainPanel <- renderUI({
      output$table <- DT::renderDataTable({
          validate(
            need(input$col1Input != "", "No column selected")
          )
          dplyr::filter(df, col1 == input$col1Input)
        })

      mainPanel(
        DT::dataTableOutput("table")
      )
  })
}

shinyApp(ui = ui, server = server)

编辑: 您可能还想过滤您 select 的特定列。您可以这样做:

ui <- fluidPage(
  uiOutput("sidebarOutput"),
  uiOutput("mainPanel")
)

server <- function(input,output){
  df <- data.frame('col1' = c(1,2,3), 'col2' = c(4,5,6))
  output$sidebarOutput <- renderUI({
    sidebarPanel(
      selectInput(inputId = 'filtercolumn',
                  label = "Select a column to filter on",
                  choices = colnames(df)),

      renderUI({selectInput(inputId = 'valuetofilter',
                  label = paste0("filtering on column: ", colnames(df[input$filtercolumn])),
                  choices = df[[input$filtercolumn]])})
      )
  })

  output$mainPanel <- renderUI({
      output$table <- DT::renderDataTable({
          validate({
            need(input$filtercolumn != "", "No column selected")
            need(input$valuetofilter != "", "No value selected")
          })

          dplyr::filter(df,(!!as.name(input$filtercolumn)) == !!input$valuetofilter) #note the unquoting
        })

      mainPanel(
        DT::dataTableOutput("table")
      )
  })
}

shinyApp(ui = ui, server = server)

感谢this回答