I am trying to save the data from the Shiny app to the data frame. Currently I do it locally with the hope that I can do it remotely later. However I have troubles even saving it locally. It does not save and then periodically RStudio asks me to terminate my R session after I quit my app. I got the code to work a couple of days ago, but now it is stuck.
I was following this example with slight modifications:
- I don't need to load the data frame in the app, so I removed
output$responses. But even if I add it back, the code still doesn't work. - I would like to load up the last entry if that exists, so I added
observeEvent(input$load....
I do not have any errors. So I'm not sure what is going on.
My code:
library(shiny)
# Define the fields we want to save from the form
fields <- c("name", "used_shiny", "r_num_years")
default_name <- ""
default_used <- FALSE
default_years <- 2
saveData <- function(data) {
data <- as.data.frame(t(data))
if (exists("responses")) {
responses <- rbind(responses, data)
} else {
responses <- data
}
}
ui = fluidPage(
#DT::dataTableOutput("responses", width = 300), tags$hr(),
textInput("name", "Name", default_name),
checkboxInput("used_shiny", "I've built a Shiny app in R before", default_used),
sliderInput("r_num_years", "Number of years using R",
0, 25, default_years, ticks = FALSE),
actionButton("submit", "Submit"),
actionButton("load", "Load")
)
server = function(input, output, session) {
# 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())
})
observeEvent(input$load, {
if (exists("responses")){
updateTextInput(session, "name", value = responses[nrow(responses), "name"])
updateCheckboxInput(session, "used_shiny", value = responses[nrow(responses) ,"used_shiny"])
updateSliderInput(session, "r_num_years", value = responses[nrow(responses) ,"r_num_years"])
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
I tried:
- creating the
responsesdata.frame manually - restarting RStudio in case of a glitch It didn't help.
I expect the code to save the input data into data.frame responses.
responses <<- dataandresponses <<- rbind(responses, data)