Scott OatleySociology / UCL
← Guides

Surveys in Shiny: an interactive guide

Build a web survey in R that stores structured responses, step by step

Companion to the workshop Survey and Questionnaire Construction: the Shiny Package in R, Edinburgh Futures Institute, November 2024.

Shiny turns R code into a web application. This workshop uses it to build a survey that does more than off-the-shelf tools: it asks for consent first, refuses to submit until required questions are answered, records how long each person took, and writes each response as a new row in a Google Sheet. Every widget below runs in your browser and shows the R code that would produce it.

1Anatomy of an app

Every Shiny app lives in one app.R file, in its own folder, and has three parts:

The key idea is reactivity: when an input changes, every output that depends on it re-runs on its own. Move the slider in this copy of the workshop’s first app.

Basic Shiny App Example

ui <- fluidPage(
  titlePanel("Basic Shiny App Example"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("num", "Choose a number:",
                  min = 1, max = 100, value = 50)),
    mainPanel(textOutput("result"))))

server <- function(input, output) {
  output$result <- renderText({
    paste("Your number multiplied by 2 is:",
          input$num * 2)
  })
}

shinyApp(ui = ui, server = server)

Noticeinput$num in the server is the slider called "num" in the ui. That shared name is how the two halves talk to each other.

2Widget workshop

Asking every question as free text gives you messy data. Widgets fix the form of the answer. Every widget takes the same first two arguments, an id (used in the server as input$id) and a label (shown to the user), then a default. Choose a widget, edit its label, and see both the widget and its code.

Try each widget

  

A design point from the workshop: for radio buttons use selected = 0, so no answer is pre-selected and nobody is nudged towards one.

3Storing responses

Saving with write.csv() only works on your own computer. Once the app is hosted on shinyapps.io it runs on a remote server, so responses need to go somewhere remote. The workshop uses Google Sheets through the googlesheets4 package: free, structured, and easy to export as .csv.

Four pieces of server code do the work:

PieceWhat it does
fields <- c("name", "used_shiny", "r_num_years")Names the inputs to save, which become the sheet’s columns
formData <- reactive(...)Collects the current value of each field into one record
save_data_gsheets() with sheet_append()Adds that record as a new row, without touching earlier rows
observeEvent(input$submit, ...)Runs the save only when Submit is clicked
Submit and watch the sheet grow

Google Sheet (simulated)

4Authentication and secrets

Every visitor to your app needs to write to the sheet, but none of them should be able to log in as you. The answer is a service account: a robot Google account that the app authenticates as.

  1. In Google Cloud Console, go to IAM and Admin, then Service Accounts, and create one.
  2. Create a key for it in JSON format and download it.
  3. Copy the service account’s email from the JSON file and share your Google Sheet with that email as an editor. Enable the Google Sheets API for the project.
  4. In your app’s folder create a .secrets folder, put the key there as service-account.json, and authenticate with gs4_auth(path = ".secrets/service-account.json").
Keep these private: the JSON key and the sheet’s URL (SHEET_ID). Anyone with either can read or change your respondents’ data. Never put them in a public repository, a slide or a handout. Sharing the sheet with the service account is enough; you do not need to make it editable by “anyone with the link”.

5Making it look like a survey

An unstyled app puts everything on the left and looks unfinished. The workshop adds a small style sheet with tags$style(HTML("...")) and wraps each question in div(class = ...). Toggle the styling to see the difference.

Styling on and off
Name*
This course seems to be worth my time*
div(class = "survey-question",
    HTML("Name<span class='mandatory-asterisk'>*</span>")),
div(class = "survey-input",
    textInput("name", label = NULL, placeholder = "Enter your name"))

Six classes do the work: survey-container (centred, 600px wide), survey-question (bold 18px), survey-input, btn-primary (green button), submit-container and mandatory-asterisk (the red star).

6The finished survey

The final app adds three pieces of logic:

The “how did you travel” checkboxes are also split into one 0/1 column per option, which is much easier to analyse than a list. Try the full flow.

Consent → survey → stored row

Stored rows (simulated sheet)

Try thisDecline consent once, then restart. Leave the travel question blank and watch the Submit button. Submit quickly, then slowly, and compare time_spent.

7Deploying

Run the app locally with the Run App button, then publish it to shinyapps.io with the Publish button. If publishing fails (for example, shinyapps.io mistakes the app for a Quarto document), deploy from the console and list the secrets folder so the key travels with the app:

rsconnect::deployApp(appDir = "your_app",
                     appPrimaryDoc = "app.R",
                     appFiles = c("app.R", ".secrets/"))

8Check yourself

9Workshop files