sd_store_value | R Documentation |
This function allows storing additional values to be included in the survey data, such as respondent IDs or other metadata. When a database connection is provided, it implements session persistence - if a value already exists for the current session, storage is skipped to maintain consistency across page refreshes.
sd_store_value(value, id = NULL, db = NULL, auto_assign = TRUE)
value |
The value to be stored. This can be any R object that can be coerced to a character string. |
id |
(Optional) Character string. The id (name) of the value in the
data. If not provided, the name of the |
db |
(Optional) Database connection object created with sd_db_connect(). If provided, enables session persistence. If not provided, will automatically look for a variable named 'db' in the calling environment, or fall back to the database connection from the session. |
auto_assign |
Logical. If |
The value that was stored (either the new value or existing value from database if session persistence applies). This allows the function to be used in variable assignments.
if (interactive()) {
library(surveydown)
# Get path to example survey file
survey_path <- system.file("examples", "sd_ui.qmd",
package = "surveydown")
# Copy to a temporary directory
temp_dir <- tempdir()
file.copy(survey_path, file.path(temp_dir, "basic_survey.qmd"))
orig_dir <- getwd()
setwd(temp_dir)
# Define a minimal server
server <- function(input, output, session) {
# Set up database connection
db <- sd_db_connect()
# Generate and store values with automatic assignment (default behavior)
respondentID <- sample(1:1000, 1)
sd_store_value(respondentID, "respID", db) # respondentID automatically updated
completion_code <- sample(0:9, 6, replace = TRUE)
sd_store_value(completion_code) # completion_code automatically updated
# Traditional assignment approach (auto_assign = FALSE)
some_value <- sd_store_value(42, "some_value", auto_assign = FALSE)
# The function ensures session persistence across page refreshes
sd_server()
}
# Run the app
shiny::shinyApp(ui = sd_ui(), server = server)
# Clean up
setwd(orig_dir)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.