Skip to content

Instantly share code, notes, and snippets.

@mkcor
Created April 24, 2018 19:28
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 mkcor/caf23ff13fda8076066f2deea328a327 to your computer and use it in GitHub Desktop.
Save mkcor/caf23ff13fda8076066f2deea328a327 to your computer and use it in GitHub Desktop.
Understanding reactive programming (baby steps).
library(ggplot2)
library(shiny)
# Global variables can go here.
values <- runif(200)
# Define the UI.
ui <- fluidPage(
radioButtons("n", "Approximate number of bins",
c(3, 5, 10), selected = 5),
plotOutput("plot")
)
# Define the server code.
server <- function(input, output) {
# The `input` object contains reactive values (implementation of reactive
# sources). They are set by input from the web browser.
# Use a reactive expression to cache the results of any procedure that happens
# in response to user input.
current_bw <- reactive({ 1 / as.numeric(input$n) })
# The `output` object is an observer (implementation of reactive endpoint).
# Observers do not return values; they have side effects.
output$plot <- renderPlot({
ggplot(as.data.frame(values), aes(values)) +
geom_histogram(binwidth = current_bw())
})
}
# Return a Shiny app object.
shinyApp(ui = ui, server = server)
@mkcor
Copy link
Author

mkcor commented Apr 25, 2018

This single-file Shiny app is up and running at: https://mkcor.shinyapps.io/reactivity/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment