Skip to content

Instantly share code, notes, and snippets.

@ptoche
Created January 16, 2014 19:31
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 ptoche/8461748 to your computer and use it in GitHub Desktop.
Save ptoche/8461748 to your computer and use it in GitHub Desktop.
Demo on a simple counter
# server.R
library("shiny")
library("shinyAce")
shinyServer(
function(input, output) {
# A reactiveValues object holds the value of the counter
values <- reactiveValues(i = 0)
# Print the value of the counter stored in values$i
output$count <- renderUI({
h5(paste0("counter = ", values$i))
})
# Display buttons in the mainPanel
output$buttons <- renderUI({
if (values$i == 0) {
list(actionButton("increment", "Next"))
} else {
if (values$i == 10) {
list(actionButton("decrement", "Back"))
} else {
list(actionButton("decrement", "Back"), actionButton("increment", "Next"))
}
}
})
# The observers re-run the code whenever the button is clicked
# Use isolate to avoid getting stuck in an infinite loop
observe({
if(is.null(input$increment) || input$increment == 0){return()}
values$i <- isolate(values$i) + 1
})
observe({
if(is.null(input$decrement) || input$decrement == 0){return()}
values$i <- isolate(values$i) - 1
})
}
)
# https://groups.google.com/forum/#!topic/shiny-discuss/IWBghVCcMnI
# ui.R
library("shiny")
library("shinyAce")
sourceCode <- list( # or save this in global.R
aceEditor("ui"
, value = paste(readLines("ui.R"), collapse = "\n")
, mode = "r"
, theme = "ambience"
, height = "400px"
, readOnly = TRUE
), br(),
aceEditor("server"
, value = paste(readLines("server.R"), collapse = "\n")
, mode = "r"
, theme = "ambience"
, height = "400px"
, readOnly = TRUE
)
)
shinyUI(
basicPage(
h4("Shiny App Demo: Reactive Counter")
,
tags$hr()
,
uiOutput("buttons")
,
uiOutput("count")
,
tags$hr()
,
helpText("Description: A counter starting at 0 and with maximum value 10")
,
tags$br()
,
checkboxInput("showSourceCode", label = "Show shiny source code?", value = FALSE)
, # 'value = FALSE' not working in Chrome
conditionalPanel(
condition = "input.showSourceCode == true", sourceCode
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment