Created
April 7, 2022 03:34
-
-
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
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
# 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