Skip to content

Instantly share code, notes, and snippets.

@aagarw30
Created April 7, 2022 03:34
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/276547832fe38507db8dcfce21855724 to your computer and use it in GitHub Desktop.
Save aagarw30/276547832fe38507db8dcfce21855724 to your computer and use it in GitHub Desktop.
Demo example for reactiveVal() with observeEvent() - Create dependency on actionButton - Subset data on click of actionButton and display in datatable
# Demo example for reactiveVal with observeEvent()
# Create dependency on a button to reflect user input changes to the rendered output
library(shiny) # for Shiny components
library(dplyr) # for piping
my = mtcars %>%
mutate(cyl = as.factor(cyl))
ui <- fluidPage(
h4("Demo of using reactiveVal() along with observeEvent() in R Shiny to subset data and display 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")
# Plot
)
server <- function(input, output, session) {
# initialize the reactive data object using reactiveVal
sub = reactiveVal()
# filtering / subsetting within the reactive function on click of action Button
observeEvent(eventExpr = input$show,
# update the data object based on use inputs
sub(dplyr::filter(my,
cyl==input$cyl,
mpg>=input$miles[1] & mpg<=input$miles[2])),
ignoreNULL = FALSE # so as to get the datatable displayed with initial selections
)
# display the subset data
output$table <- renderTable({
sub()
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment