Last active
September 8, 2023 20:25
-
-
Save wch/4211337 to your computer and use it in GitHub Desktop.
Shiny example: dynamic input fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data_sets <- c("mtcars", "morley", "rock") | |
shinyServer(function(input, output) { | |
# Drop-down selection box for which data set | |
output$choose_dataset <- renderUI({ | |
selectInput("dataset", "Data set", as.list(data_sets)) | |
}) | |
# Check boxes | |
output$choose_columns <- renderUI({ | |
# If missing input, return to avoid error later in function | |
if(is.null(input$dataset)) | |
return() | |
# Get the data set with the appropriate name | |
dat <- get(input$dataset) | |
colnames <- names(dat) | |
# Create the checkboxes and select them all by default | |
checkboxGroupInput("columns", "Choose columns", | |
choices = colnames, | |
selected = colnames) | |
}) | |
# Output the data | |
output$data_table <- renderTable({ | |
# If missing input, return to avoid error later in function | |
if(is.null(input$dataset)) | |
return() | |
# Get the data set | |
dat <- get(input$dataset) | |
# Make sure columns are correct for data set (when data set changes, the | |
# columns will initially be for the previous data set) | |
if (is.null(input$columns) || !(input$columns %in% names(dat))) | |
return() | |
# Keep the selected columns | |
dat <- dat[, input$columns, drop = FALSE] | |
# Return first 20 rows | |
head(dat, 20) | |
}) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
shinyUI(pageWithSidebar( | |
headerPanel(""), | |
sidebarPanel( | |
uiOutput("choose_dataset"), | |
uiOutput("choose_columns"), | |
br(), | |
a(href = "https://gist.github.com/4211337", "Source code") | |
), | |
mainPanel( | |
tableOutput("data_table") | |
) | |
)) |
cool code
Thank you!
i just needed this for my project
Thank you! Clean and useful code.
Very useful example, thank you!!
could you show an example where plots are rendered, rather than tables? it will be great. i have done something similar to this, but when i unselect the first checkbox, i get errors. my code only works when the first checkbox is mandatorily selected and others are checked/unchecked
@SmritiSatyan: I am looking for similar thing. Did you get the solution?
I searched "dynamic query ui shiny" and I've found this useful code. Thanks. :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!!!