Skip to content

Instantly share code, notes, and snippets.

@aagarw30
Last active April 5, 2022 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aagarw30/84c8e19ca5baf7100d3ca95fdcc4baef to your computer and use it in GitHub Desktop.
Save aagarw30/84c8e19ca5baf7100d3ca95fdcc4baef to your computer and use it in GitHub Desktop.
Demo eventReactive() - subset data on click of button and display the resultant data
# Demo example for eventReactive()
# Create dependency on a button to reflect user input changes to the rendered output
# subset data on click of button and display the resultant data
# Load the required libraries
library(shiny) # for Shiny components
library(dplyr) # for piping and data manipulation
# For demo using the mtcars dataset
# convert the cylinder variable to factor type
my = mtcars %>%
mutate(cyl = as.factor(cyl))
## ui component starts here
ui <- fluidPage(
h3("Demo on eventReactive() function"),
h4("Use case - Subset dataset basis user selection and display subset data on click of action button"),
hr(),
# SliderInput
sliderInput(inputId = "miles",
label ="Select miles per gallon range",
dragRange = TRUE,
min= min(my$mpg),
max = max(my$mpg),
value = c(15, 25)
),
#RadioButton
radioButtons(inputId = "cyl" ,
label ="Select the cylinder #" ,
choices =levels((my$cyl)) ,
selected = 4,
inline = TRUE),
# Action button
actionButton(inputId ="show" ,label = "Show Data"),
# Data Table
tableOutput("table")
)
server <- function(input, output, session) {
filter <- eventReactive(eventExpr = input$show,
valueExpr = {
dplyr::filter(my,
cyl==input$cyl,
mpg>=input$miles[1] & mpg<=input$miles[2])
}, ignoreNULL = FALSE
)
# Display the filtered table
output$table <- renderTable({
filter()
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment