Created
March 26, 2025 22:34
-
-
Save Aariq/8e5222abd08f147242dc30dba5d0cafd to your computer and use it in GitHub Desktop.
This file contains hidden or 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
library(shiny) | |
library(tibble) | |
library(dplyr) | |
df <- tibble( | |
ID = 1:5, | |
age = c("21-30", "21-30", "31-40", "31-40", "70+"), | |
hispanic_bin = c(1, 0, 1, 0, 1), | |
white_bin = c(1, 1, 1, 0, 0), | |
black_bin = c(0, 0, 0, 1, 1) | |
) | |
# df | |
# # A tibble: 5 × 5 | |
# ID age hispanic_bin white_bin black_bin | |
# <int> <chr> <dbl> <dbl> <dbl> | |
# 1 1 21-30 1 1 0 | |
# 2 2 21-30 0 1 0 | |
# 3 3 31-40 1 1 0 | |
# 4 4 31-40 0 0 1 | |
# 5 5 80+ 1 0 1 | |
# Define UI | |
ui <- fluidPage( | |
# Sidebar with select widgets | |
sidebarLayout( | |
sidebarPanel( | |
selectInput( | |
"age", | |
"age", | |
choices = c("21-30", "31-40", "41-50", "51-60", "61-70", "70+"), | |
multiple = TRUE | |
), | |
selectInput( | |
"race", | |
"race/ethnicity", | |
choices = c( | |
#what shows up in the app = binary column name in dataset | |
"White" = "white_bin", | |
"Black" = "black_bin", | |
"Hispanic" = "hispanic_bin" | |
), | |
multiple = TRUE | |
) | |
), | |
# filtered data output | |
tableOutput("df_filtered") | |
) | |
) | |
# Define server logic to do filtering | |
server <- function(input, output) { | |
output$df_filtered <- renderTable({ | |
df |> | |
filter( | |
# you are right that you need the if else statment here, ifelse() | |
# doesn't work, but checking that input isn't NULL is enough | |
if (!is.null(input$age)) age %in% input$age else TRUE, | |
# This should show all race values if nothing is selected | |
if_any(input$race, \(x) x == 1) | |
) | |
}) | |
} | |
# Run the application | |
shinyApp(ui = ui, server = server) | |
# https://gist.github.com/Aariq/8e5222abd08f147242dc30dba5d0cafd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment