对于动态 UI,基本上有两种方法可以选择:updateXXX
或renderUI
. 这是采用这种updateXXX
方法的解决方案。
library(shiny)
ui <- fluidPage(sidebarLayout(
sidebarPanel(
selectInput("dataset", "choose a dataset", c("mtcars", "iris")),
selectInput("column", "select column", "placeholder1"),
selectInput("level", "select level", "placeholder2")
),
mainPanel(tableOutput("table"))
))
server <- function(input, output, session){
dataset <- reactive({
get(input$dataset)
})
observe({
updateSelectInput(session, "column", choices = names(dataset()))
})
observeEvent(input$column, {
column_levels <- as.character(sort(unique(
dataset()[[input$column]]
)))
updateSelectInput(session, "level", choices = column_levels)
})
output$table <- renderTable({
subset(dataset(), dataset()[[input$column]] == input$level)
})
}
shinyApp(ui, server)
在server
函数中,有一行
updateSelectInput(session, "level", choices = column_levels)
它更新了choices
第三个下拉菜单的参数level
。要计算级别,您可以使用该base::levels
函数,但这不适用于 numerc columns。因此我用
as.character(sort(unique( . )))
反而。“占位符”将在启动后立即被替换。
使用 fileInput 创建的数据框
下面的代码显示了如何将此逻辑与fileInput
. 只要没有选择文件,我就在其中添加了一个隐藏下拉conitionalPanel
菜单。ui
见这里。
library(shiny)
# test data
write.csv(reshape2::tips, "tips.csv", row.names = FALSE)
write.csv(mtcars, "mtcars.csv")
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput('datafile', 'Choose CSV file',
accept = c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
conditionalPanel(
# use a server side condition
condition = "output.fileUploaded",
# placeholders will be replaced from the server
selectInput("pic", "Primay C", "placeholder 1"),
selectInput("level", "select level", "placeholder 2")
)
),
mainPanel(
h3("filtered data"),
tableOutput("table")
)
)
)
server <- function(input, output, session){
# create reactive version of the dataset (a data.frame object)
filedata <- reactive({
infile <- input$datafile
if (is.null(infile))
# User has not uploaded a file yet. Use NULL to prevent observeEvent from triggering
return(NULL)
temp <- read.csv(infile$datapath)
temp[order(temp[, 1]),]
})
# inform conditionalPanel wheter dropdowns sohould be hidden
output$fileUploaded <- reactive({
return(!is.null(filedata()))
})
outputOptions(output, 'fileUploaded', suspendWhenHidden=FALSE)
# update the selectInput elements according to the dataset
## update 'column' selector
observeEvent(filedata(), {
updateSelectInput(session, "pic", choices = names(filedata()))
})
## update 'level' selector
observeEvent(input$pic, {
column_levels <- unique(filedata()[[input$pic]])
updateSelectInput(session, "level", choices = column_levels,
label = paste("Choose level in", input$pic))
}, ignoreInit = TRUE)
# show table
output$table <- renderTable({
subset(filedata(), filedata()[[input$pic]] == input$level)
}, bordered = TRUE)
}
shinyApp(ui, server)