我正在使用闪亮的应用程序上的过滤器来过滤数据框。目前,我必须手动将可能的值输入到ui中。有没有办法从服务器数据框中读取唯一值并使用该列表填充输入选项?我知道可以通过使表成为全局表来做到这一点,但是我试图避免这样做。
示例代码:
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)
谢谢!
答案 0 :(得分:2)
您可以使用renderUI从服务器构建UI。然后,您可以简单地使用服务器中数据框中的列之一来构建您的选择输入?
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)
修改: 您可能还想对所选的特定列进行过滤。您可以这样操作:
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的回答