Created
May 20, 2022 09:12
-
-
Save ChrisBeeley/e3b33af427b40c35f106634c4aab8149 to your computer and use it in GitHub Desktop.
Test file saving on Shiny server
This file contains hidden or 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
# Shiny app with 3 fields that the user can submit data for | |
ui <- fluidPage( | |
DT::dataTableOutput("responses", width = 300), tags$hr(), | |
textInput("name", "Name", ""), | |
checkboxInput("used_shiny", "I've built a Shiny app in R before", FALSE), | |
sliderInput("r_num_years", "Number of years using R", | |
0, 25, 2, ticks = FALSE), | |
actionButton("submit", "Submit") | |
) | |
server <- function(input, output) { | |
# Whenever a field is filled, aggregate all form data | |
formData <- reactive({ | |
data <- sapply(fields, function(x) input[[x]]) | |
data | |
}) | |
# When the Submit button is clicked, save the form data | |
observeEvent(input$submit, { | |
saveData(formData()) | |
}) | |
# Show the previous responses | |
# (update with current response when Submit is clicked) | |
output$responses <- DT::renderDataTable({ | |
input$submit | |
loadData() | |
}) | |
outputDir <- "responses" | |
saveData <- function(data) { | |
data <- t(data) | |
# Create a unique file name | |
fileName <- sprintf("%s_%s.csv", as.integer(Sys.time()), digest::digest(data)) | |
# Write the file to the local system | |
write.csv( | |
x = data, | |
file = file.path(outputDir, fileName), | |
row.names = FALSE, quote = TRUE | |
) | |
} | |
loadData <- function() { | |
# Read all the files into a list | |
files <- list.files(outputDir, full.names = TRUE) | |
data <- lapply(files, read.csv, stringsAsFactors = FALSE) | |
# Concatenate all data together into one data.frame | |
data <- do.call(rbind, data) | |
data | |
} | |
# Define the fields we want to save from the form | |
fields <- c("name", "used_shiny", "r_num_years") | |
} | |
shinyApp(ui = ui, server = server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment