Skip to content

Import your data to R using the `formr` package

Ulrik Lyngs edited this page Aug 20, 2021 · 4 revisions

If you use R and RStudio, then the best way to get your survey data out of form{r} is to use the formr R package to log in and download your data. For this example, we'll assume you'll put your code for downloading your data in an R Markdown file.

Step 1: Install the formr package

Install the formr package by running these commands in an R console:

install.packages("remotes")
remotes::install_github("rubenarslan/formr")

Step 2: Use best practices for your credentials

You will want to follow best practices in keeping your credentials private, so you should not put your actual username and password in the R Markdown file.

There's a number of ways to do it; the simple way we show here is by storing your log-in details in a hidden R file that you access from the R Markdown file, but don't share with others.

Create a file, for example named .passwords.R, where your log-in email and password are stored in a variable called credentials:

credentials <- list(email = "[email protected]", password = "yourpassword")

Step 3: Download data from a survey

Now create an R Markdown file, for example named download-data.Rmd.

In a code chunk in this file, load the passwords.R file (with source), connect to formr with formr::formr_connect and the information in the credentials variable from passwords.R, then download the survey data with formr::form_results:

source(".passwords.R")

formr::formr_connect(credentials$email,
credentials$password)

survey_data <- formr::formr_raw_results("survey_name")

# or do this to include question labels and 
# automatically reverse-score items whose name ends in "R":
survey_data_w_full_info <- formr::formr_results("survey_name")

"survey_name" here is whatever you have named your survey on formr.org, i.e. the name you see in big letters in the top left, to the left of 'Survey ID:'.

Step 4: Store your data

You might just store the data into a CSV:

write.csv(survey_data, "survey_data.csv")

However, one of the advantages of downloading with the formr package instead of clicking 'export results' on formr.org is that the object you download with the formr::formr_results function includes e.g. the labels for your response options.

That is, you might have data where responses to "what degree do you study for" are now numeric, and e.g. a '2' means 'undergraduate degree'. If you export a CSV from formr.org, this information is dropped.

Therefore, instead of storing your data as a CSV, you may want to store itas an R object like so:

saveRDS(survey_data_w_full_info, "survey_data_full.RDS")
# read in with readRDS("survey_data_full.RDS")