Skip to content

Instantly share code, notes, and snippets.

@aagarw30
Last active April 23, 2020 22:04
Show Gist options
  • Save aagarw30/69feeeb7e813788a753b71ef8c0877eb to your computer and use it in GitHub Desktop.
Save aagarw30/69feeeb7e813788a753b71ef8c0877eb to your computer and use it in GitHub Desktop.
Simple counter using reactiveValues() in R Shiny - An example
Title: reactiveValues() function
Description: With reactiveValues(), you can create your own reactive values. reactiveValues() Creates a list of objects that can be manipulated within a reactive context (within observer or observerEvent with dependency on changes in certain input or state of an object). reactiveValues() objects are not reactive themselves and do not re-execute themselves when input value changes unlike reactive objects. Powered by R, Shiny, and RStudio.
License: GPL-3
Author: Abhinav Agrawal
DisplayMode: Showcase
Tags: R, R Shiny,reactiveValues(), observeEvent()
Type: Shiny
library(shiny)
shinyServer(
function(input, output, session) {
counter <- reactiveValues(countervalue = 0) # Defining & initializing the reactiveValues object
observeEvent(input$add1, {
counter$countervalue <- counter$countervalue + 1 # if the add button is clicked, increment the value by 1 and update it
})
observeEvent(input$sub1, {
counter$countervalue <- counter$countervalue - 1 # if the sub button is clicked, decrement the value by 1 and update it
})
observeEvent(input$reset, {
counter$countervalue <- 0 # if the reset button is clicked, set the counter value to zero
})
output$count <- renderText({
paste("Counter Value is ", counter$countervalue) # print the latest value stored in the reactiveValues object
})
}
)
library(shiny)
shinyUI(
fluidPage(
tags$b("Simple counter using reactiveValues() - An example"),
br(),
actionButton("add1", "+ 1"),
actionButton("sub1", "- 1"),
actionButton("reset", "set to 0"),
br(),
textOutput("count")
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment