Skip to content

Instantly share code, notes, and snippets.

@mgei
Created February 24, 2020 15:14
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 mgei/5bdfac5167194c6a6ddd885b33671faf to your computer and use it in GitHub Desktop.
Save mgei/5bdfac5167194c6a6ddd885b33671faf to your computer and use it in GitHub Desktop.
persistent data storage of user input in R Shiny
library(shiny)
library(shinyWidgets)
library(tidyverse)
# read persistent data or create a new file if it does not exist yet
if ("favs.csv" %in% list.files()) {
favs <- read_file("favs.csv") %>%
strsplit(", ") %>%
.[[1]] %>%
as.numeric() %>%
.[-1]
} else {
favs <- 99
paste(favs, collapse = ", ") %>% write_file("favs.csv")
favs <- favs[-1]
}
ui <- fluidPage(
radioGroupButtons(
inputId = "fav_number",
label = "What's your favorite number?",
choices = 1:9
),
circleButton("button_go", "Go!"),
plotOutput("plot")
)
server <- function(input, output, session) {
rfavs <- reactiveVal(favs)
observeEvent(input$button_go, {
req(input$fav_number)
write_file(paste0(", ", input$fav_number), "favs.csv", append = T)
isolate({
rfavs(c(rfavs(), as.integer(input$fav_number)))
})
})
output$plot <- renderPlot({
hist(rfavs(), breaks = 1:9)
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment