| Title: | Companion R Package for the 'formr' Survey Framework |
|---|---|
| Description: | Serves as a companion toolkit for the 'formr' survey framework (<https://rforms.org>). The package acts as a bridge between a 'formr' server and a local R environment. Key features include an API client for fetching, type-casting, and automatically scoring data; a project management workflow for syncing study assets (surveys, CSS) for local editing; and functions for use within 'formr' runs to generate dynamic, personalized feedback plots and to simplify survey logic. |
| Authors: | Ruben Arslan [aut, cre] (ORCID: <https://orcid.org/0000-0002-6670-5658>), Tim B Seidel [aut, ctb] |
| Maintainer: | Ruben Arslan <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.1.2 |
| Built: | 2026-06-12 17:48:40 UTC |
| Source: | https://github.com/rubenarslan/formr |
An environment that the rforms.org server fills with per-request state
when R code runs inside an OpenCPU session on a formr study (for
example, on a CalculateUnit page or an OverviewScriptPage). Useful
fields the server may set:
.formr.formr
An environment.
.formr$run_name – the name of the current run.
.formr$host – the API host (e.g. https://api.rforms.org).
.formr$access_token – a short-lived OAuth token for the request.
.formr$last_action_time / .formr$last_action_date – timestamps
used by time_passed() and the other shorthands.
Several user-facing functions (e.g. formr_api_authenticate(),
formr_api_results(), formr_overview_sankey()) default their host
/ run_name / access_token arguments to these fields, so the same
code runs unchanged locally and on a formr study. Outside a formr
session the environment is empty.
An environment holding per-request state in its bindings (the
run_name, host, access_token, last_action_time and
last_action_date fields listed above). .formr is a data object, not a
function, so it does not itself return a value; the rforms.org server
populates these bindings before user code runs and the environment is empty
outside a formr/OpenCPU session.
Escapes any special RegExp characters in the search term. A way to check whether the search term
(e.g. a variable name) is the beginning.
Just a simple shorthand so that inexperienced R users won't have to use somewhat complex functions such as grepl() and stringr::str_detect().
You can also use \%starts_with\%.
haystack %begins_with% needlehaystack %begins_with% needle
haystack |
string in which you search |
needle |
string to search for |
A logical vector, TRUE where haystack begins with needle.
"1, 3, 4" %begins_with% "1" # TRUE "1, 3, 4" %begins_with% 1 # unlike str_detect casts all needles as characters "1, 3, 4" %begins_with% "." # FALSE"1, 3, 4" %begins_with% "1" # TRUE "1, 3, 4" %begins_with% 1 # unlike str_detect casts all needles as characters "1, 3, 4" %begins_with% "." # FALSE
Looks for a string appearing on its own. This is needed e.g.
when checking whether the replies to a mmc item, stored as a
comma-separated list from 1 to 12 contain option 1 - you wouldn't
want to get a hit for 11 and 12.
Only works for search terms containing alphanumeric characters.
Just a simple shorthand so that inexperienced R users don't have
to use somewhat complex functions such as grepl() and stringr::str_detect().
haystack %contains_word% needlehaystack %contains_word% needle
haystack |
string in which you search |
needle |
string to search for |
A logical vector, TRUE where haystack contains needle as a whole word.
"1, 3, 4" %contains_word% "1" # TRUE "1, 3, 4" %contains_word% 1 # TRUE unlike str_detect casts all needles as characters "12, 14, 17" %contains_word% "1" # FALSE even though 12 contains 1"1, 3, 4" %contains_word% "1" # TRUE "1, 3, 4" %contains_word% 1 # TRUE unlike str_detect casts all needles as characters "12, 14, 17" %contains_word% "1" # FALSE even though 12 contains 1
Just a simple shorthand so that inexperienced R users don't have
to use somewhat complex functions such as grepl() and stringr::str_detect()
with non-default arguments (e.g. fixed params).
haystack %contains% needlehaystack %contains% needle
haystack |
string in which you search |
needle |
string to search for |
A logical vector, TRUE where haystack contains needle as a fixed substring.
"1, 2, 3, 4, you" %contains% "you" "1, 2, 3, 4, you" %contains% 1 # unlike str_detect casts all needles as characters "1, 2, 3, 4, you" %contains% 343"1, 2, 3, 4, you" %contains% "you" "1, 2, 3, 4, you" %contains% 1 # unlike str_detect casts all needles as characters "1, 2, 3, 4, you" %contains% 343
Escapes any special RegExp characters in the search term. A way to check whether the search term (e.g. a variable name) is the ending.
Just a simple shorthand so that inexperienced R users don't have
to use somewhat complex functions such as grepl() and stringr::str_detect().
haystack %ends_with% needlehaystack %ends_with% needle
haystack |
string in which you search |
needle |
string to search for |
A logical vector, TRUE where haystack ends with needle.
"1, 3, 4" %ends_with% "4" # TRUE "1, 3, 4" %ends_with% 4 # unlike str_detect casts all needles as characters "1, 3, 4" %ends_with% "." # FALSE"1, 3, 4" %ends_with% "4" # TRUE "1, 3, 4" %ends_with% 4 # unlike str_detect casts all needles as characters "1, 3, 4" %ends_with% "." # FALSE
Copied from codebook.
The resulting variables will have the attribute scale_item_names containing
the basis for aggregation. Its label attribute will refer to the common stem of the
aggregated variable names (if any), the number of variables, and the
aggregation function.
aggregate_and_document_scale(items, fun = rowMeans, stem = NULL)aggregate_and_document_scale(items, fun = rowMeans, stem = NULL)
items |
data.frame of the items that should be aggregated |
fun |
aggregation function, defaults to rowMeans with na.rm = FALSE |
stem |
common stem for the variables, specify if it should not be auto-detected as the longest common stem of the variable names |
A numeric vector (the aggregated scale score) carrying scale_item_names and label attributes.
testdf <- data.frame(bfi_neuro_1 = rnorm(20), bfi_neuro_2 = rnorm(20), bfi_neuro_3R = rnorm(20), age = rpois(20, 30)) item_names <- c('bfi_neuro_1', 'bfi_neuro_2', 'bfi_neuro_3R') testdf$bfi_neuro <- aggregate_and_document_scale(testdf[, item_names]) testdf$bfi_neurotestdf <- data.frame(bfi_neuro_1 = rnorm(20), bfi_neuro_2 = rnorm(20), bfi_neuro_3R = rnorm(20), age = rpois(20, 30)) item_names <- c('bfi_neuro_1', 'bfi_neuro_2', 'bfi_neuro_3R') testdf$bfi_neuro <- aggregate_and_document_scale(testdf[, item_names]) testdf$bfi_neuro
Convert formr run structure to data.frame
## S3 method for class 'formr_api_run_structure' as.data.frame(x, ...)## S3 method for class 'formr_api_run_structure' as.data.frame(x, ...)
x |
The object. |
... |
Additional arguments. |
A data.frame with one row per unit and columns position, type, description and details.
This function just turns a formr_item_list into a data.frame. The reason, these lists don't come as data.frames as default is because the 'choices' are a list themselves. When transforming, the choice column contains a collapsed choice list, which may be less useful for some purposes.
## S3 method for class 'formr_item_list' as.data.frame(x, row.names, ...)## S3 method for class 'formr_item_list' as.data.frame(x, row.names, ...)
x |
a formr_item_list |
row.names |
not used |
... |
not used |
A data.frame of item metadata, one row per item, with choices
collapsed to a comma-separated string.
## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) as.data.frame(formr_items(survey_name = 'training_diary' )) ## End(Not run) items = formr_items(path = system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE)) items_df = as.data.frame(items) items_df[1,]## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) as.data.frame(formr_items(survey_name = 'training_diary' )) ## End(Not run) items = formr_items(path = system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE)) items_df = as.data.frame(items) items_df[1,]
This slightly modifies the knitr::knit_child() function to have different defaults.
the environment defaults to the calling environment.
the output receives the class knit_asis, so that the output will be rendered "as is" by knitr when calling inside a chunk (no need to set results='asis' as a chunk option).
defaults to quiet = TRUE
asis_knit_child( input = NULL, text = NULL, ..., quiet = TRUE, options = NULL, envir = parent.frame() )asis_knit_child( input = NULL, text = NULL, ..., quiet = TRUE, options = NULL, envir = parent.frame() )
input |
if you specify a file path here, it will be read in before being passed to knitr (to avoid a working directory mess) |
text |
passed to |
... |
passed to |
quiet |
passed to |
options |
defaults to NULL. |
envir |
passed to |
Why default to the calling environment? Typically this function defaults to the global environment. This makes sense if you want to use knit_children in the same context as the rest of the document. However, you may also want to use knit_children inside functions to e.g. summarise a regression using a set of commands (e.g. plot some diagnostic graphs and a summary for a regression nicely formatted).
Some caveats:
the function has to return to the top-level. There's no way to cat() this from loops or an if-condition without without setting results='asis'. You can however concatenate these objects with paste.knit_asis()
A length-1 character string of class knit_asis (the knitted child document).
## Not run: # Not run: requires a knitr session and an external child .Rmd document. # an example of a wrapper function that calls asis_knit_child with an argument # ensures distinct paths for cache and figures, so that these calls can be looped in parallel regression_summary = function(model) { child_hash = digest::digest(model) options = list( fig.path = paste0(knitr::opts_chunk$get("fig.path"), child_hash, "-"), cache.path = paste0(knitr::opts_chunk$get("cache.path"), child_hash, "-")) asis_knit_child("_regression_summary.Rmd", options = options) } ## End(Not run)## Not run: # Not run: requires a knitr session and an external child .Rmd document. # an example of a wrapper function that calls asis_knit_child with an argument # ensures distinct paths for cache and figures, so that these calls can be looped in parallel regression_summary = function(model) { child_hash = digest::digest(model) options = list( fig.path = paste0(knitr::opts_chunk$get("fig.path"), child_hash, "-"), cache.path = paste0(knitr::opts_chunk$get("cache.path"), child_hash, "-")) asis_knit_child("_regression_summary.Rmd", options = options) } ## End(Not run)
formr display labels for multiple choice items, but stores their values. We assume you prefer to analyse the values (e.g. numeric values for Likert-type items, or English values for international surveys), but sometimes you may wish to switch this around.
choice_labels_for_values(survey, item_name)choice_labels_for_values(survey, item_name)
survey |
survey with item_list attribute |
item_name |
item name |
A vector of choice labels mapped onto the supplied item values.
example(formr_post_process_results) table(processed_results$BFIK_extra_4) table(choice_labels_for_values(processed_results, "BFIK_extra_4"))example(formr_post_process_results) table(processed_results$BFIK_extra_4) table(choice_labels_for_values(processed_results, "BFIK_extra_4"))
Just a simple shorthand to get the current element (in a formr df, where the last element is always the one from the current session).
current(x)current(x)
x |
vector of which you want the current element |
A length-1 vector (the last element of x), keeping x's type.
current( c(1:10,NA) ) current( 1:10 )current( c(1:10,NA) ) current( 1:10 )
can be used as an argument to knitr::opts_knit. If you attach the images properly, you can then send knit emails including plots. See the formr OpenCPU module on Github for a sample implementation.
email_image(x, ext = ".png")email_image(x, ext = ".png")
x |
image ID |
ext |
extension, defaults to .png |
A length-1 character string holding a cid: reference for inline email images,
carrying the source path in its link attribute.
## Not run: # Not run: meant to run inside a knitr session as the figure upload hook. library(knitr); library(formr) opts_knit$set(upload.fun=formr::email_image) ## End(Not run)## Not run: # Not run: meant to run inside a knitr session as the figure upload hook. library(knitr); library(formr) opts_knit$set(upload.fun=formr::email_image) ## End(Not run)
Just a simple to check how many times a survey (e.g. diary) has expired (i.e. user missed it). It defaults to checking the "expired" variable for this.
expired(survey, variable = "expired")expired(survey, variable = "expired")
survey |
which survey are you asking about? |
variable |
which variable should be filled out, defaults to "ended" |
An integer: the count of expired sessions (non-missing values in
survey[[variable]]).
survey = data.frame(expired = c(NA, "2016-05-29 10:11:00", NA)) expired(survey = survey)survey = data.frame(expired = c(NA, "2016-05-29 10:11:00", NA)) expired(survey = survey)
If you pass in a z-standardised value (x - Mean)/SD, and a vector of feedback text chunks, that has either three or five elements, the text chunks will be used in this order [very low], low, average, high, [very high] corresponding to these intervals [low, -2], [-2, -1], [-1, 1], [1, 2], [2, high]
feedback_chunk(normed_value, chunks)feedback_chunk(normed_value, chunks)
normed_value |
a z-standardised value |
chunks |
a three or five element long character vector containing the text chunks for feedback |
A length-1 character string: the chunk selected for the interval containing normed_value.
feedback_chunk(normed_value = 0.7, chunks = c("You are rather introverted.", "You're approximately as extraverted as most people.","You are rather extraverted."))feedback_chunk(normed_value = 0.7, chunks = c("You are rather introverted.", "You're approximately as extraverted as most people.","You are rather extraverted."))
Just a simple to check how many times a survey (e.g. diary) was finished. It defaults to checking the "ended" variable for this.
finished(survey, variable = "ended")finished(survey, variable = "ended")
survey |
which survey are you asking about? |
variable |
which variable should be filled out, defaults to "ended" |
An integer: the count of non-missing values in survey[[variable]]
(0 when the survey or column is empty).
survey = data.frame(ended = c("2016-05-28 10:11:00", NA, "2016-05-30 11:18:28")) finished(survey = survey)survey = data.frame(ended = c("2016-05-28 10:11:00", NA, "2016-05-30 11:18:28")) finished(survey = survey)
Just a simple shorthand to get the first, non-missing argument per default.
Can give more than one element and can include missing elements.
The inverse of last().
first(x, n = 1, na.rm = TRUE)first(x, n = 1, na.rm = TRUE)
x |
vector of which you want the first element |
n |
number of elements to take from the beginning |
na.rm |
whether to remove missings first, defaults to TRUE |
A vector of the same type as x holding its first n elements
(after dropping NAs when na.rm = TRUE); an empty vector if none remain.
first( c(NA,1:10) ) first( c(NA, 1:10), 2, TRUE )first( c(NA,1:10) ) first( c(NA, 1:10), 2, TRUE )
If you've retrieved an item table using formr_items() you can use this
function to aggregate your multiple choice items into mean scores.
If you do not have a item table (e.g. your data was not collected using formr, you don't want another HTTP request in a time-sensitive process).
Example: If your data contains Extraversion_1, Extraversion_2R and Extraversion_3, there will be two new variables in the result: Extraversion_2 (reversed to align with _1 and _2) and Extraversion, the mean score of the three.
formr_aggregate( survey_name, item_list = formr_items(survey_name, host = host), results = formr_raw_results(survey_name, host = host), host = formr_last_host(), compute_alphas = FALSE, fallback_max = 5, plot_likert = FALSE, quiet = FALSE, aggregation_function = rowMeans, ... )formr_aggregate( survey_name, item_list = formr_items(survey_name, host = host), results = formr_raw_results(survey_name, host = host), host = formr_last_host(), compute_alphas = FALSE, fallback_max = 5, plot_likert = FALSE, quiet = FALSE, aggregation_function = rowMeans, ... )
survey_name |
case-sensitive name of a survey your account owns |
item_list |
an item_list, will be auto-retrieved based on survey_name if omitted |
results |
survey results, will be auto-retrieved based on survey_name if omitted |
host |
defaults to |
compute_alphas |
deprecated, functionality migrated to codebook package |
fallback_max |
defaults to 5 - if the item_list is set to null, we will use this to reverse |
plot_likert |
deprecated, functionality migrated to codebook package |
quiet |
defaults to FALSE - If set to true, likert plots and reliability computations are not echoed. |
aggregation_function |
defaults to rowMeans with na.rm = FALSE |
... |
formerly passed to |
The results data.frame with one added numeric column per scale (the row mean of its items).
results = jsonlite::fromJSON(txt = system.file('extdata/gods_example_results.json', package = 'formr', mustWork = TRUE)) items = formr_items(path = system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE)) results = formr_recognise(item_list = items, results = results) agg = formr_aggregate(item_list = items, results = results, compute_alphas = FALSE, plot_likert = FALSE) agg[, c('religiousness', 'prefer')]results = jsonlite::fromJSON(txt = system.file('extdata/gods_example_results.json', package = 'formr', mustWork = TRUE)) items = formr_items(path = system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE)) results = formr_recognise(item_list = items, results = results) agg = formr_aggregate(item_list = items, results = results, compute_alphas = FALSE, plot_likert = FALSE) agg[, c('religiousness', 'prefer')]
Aggregate Scales
formr_api_aggregate(results, item_list, min_items = 2)formr_api_aggregate(results, item_list, min_items = 2)
results |
A data frame/tibble containing the run results. |
item_list |
A data frame containing item metadata (names, types, choices). |
min_items |
Minimum number of valid items required to calculate a mean (default 2). |
The results data.frame with one added numeric column per scale (the row mean of its items); scale reliability stored in attributes.
Connects to the API. If no credentials are provided, the auto-pickup
chain is: the package's hidden .formr env (set automatically when
the code runs inside an OpenCPU session on rforms.org), then the
calling-frame chain (for legacy injectors that wrote bare locals into
the wrapper scope), then the keyring.
formr_api_authenticate( host = "https://rforms.org", client_id = NULL, client_secret = NULL, access_token = NULL, account = NULL, verbose = TRUE )formr_api_authenticate( host = "https://rforms.org", client_id = NULL, client_secret = NULL, access_token = NULL, account = NULL, verbose = TRUE )
host |
API Base URL. Defaults to |
client_id |
OAuth Client ID. |
client_secret |
OAuth Client Secret. |
access_token |
Direct Access Token. |
account |
Optional string identifier for multiple accounts on the same host. |
verbose |
Logical. If TRUE (default), reports success via |
Invisibly NULL; called for its side effect of obtaining and caching an OAuth access token (errors on failure).
Downloads the full run structure, all survey items, attached files, and results. Saves everything into a structured folder.
formr_api_backup_run(run_name, dir = NULL, prompt = TRUE, verbose = TRUE)formr_api_backup_run(run_name, dir = NULL, prompt = TRUE, verbose = TRUE)
run_name |
Name of the run/study. |
dir |
Directory to write the backup into. Defaults to a sub-folder named
after the run inside |
prompt |
Logical. If TRUE (default), asks for confirmation before
overwriting when run interactively; in a non-interactive session it errors
instead of proceeding unattended. Pass |
verbose |
Logical. If TRUE (default), reports progress via |
Invisibly NULL; called for its side effect of writing the run
structure (JSON), surveys, files and results (results.rds) into dir.
## Not run: # Not run: needs a live formr server and an authenticated session. formr_api_backup_run("my_run", dir = tempdir()) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_api_backup_run("my_run", dir = tempdir()) ## End(Not run)
Creates one or more new runs on the server. Prints a confirmation message with the public link for each.
formr_api_create_run(name, verbose = TRUE)formr_api_create_run(name, verbose = TRUE)
name |
A character vector of names for the new runs (must be unique). |
verbose |
Logical. If TRUE (default), reports progress via |
Invisibly returns a data frame containing the name and link of the created runs.
Creates one or more sessions. If codes is NULL, one random session is created.
If codes is provided, tries to create sessions with those specific codes.
formr_api_create_session( run_name, codes = NULL, testing = FALSE, verbose = TRUE )formr_api_create_session( run_name, codes = NULL, testing = FALSE, verbose = TRUE )
run_name |
Name of the run. |
codes |
Character vector of codes. If NULL, creates one random code. |
testing |
Logical. Mark these sessions as testing? |
verbose |
Logical. If TRUE (default), reports progress via |
Invisibly the API response: a list with the created sessions and,
for any that failed, an errors data.frame to inspect.
CAUTION: This will permanently remove every file attached to the specified run. It first fetches the list of existing files, then iterates through them to delete.
formr_api_delete_all_files(run_name, prompt = TRUE, verbose = TRUE)formr_api_delete_all_files(run_name, prompt = TRUE, verbose = TRUE)
run_name |
Name of the run. |
prompt |
Logical. If TRUE (default), asks for interactive confirmation before deleting; in a non-interactive session it errors instead of proceeding unattended. Set to FALSE for automated scripts (use with care). |
verbose |
Logical. If TRUE (default), reports progress via |
Invisibly TRUE on success; called to delete all files from the run.
Removes file attachment(s) from the run. Accepts a single filename, a vector of filenames, or a local directory path (which will delete files on the server that match the names of the files in the local directory).
formr_api_delete_file(run_name, file_name, verbose = TRUE)formr_api_delete_file(run_name, file_name, verbose = TRUE)
run_name |
Name of the run. |
file_name |
The name of the file(s) to delete (e.g. "image.png"), or a local directory path. |
verbose |
Logical. If TRUE (default), reports progress via |
Invisibly TRUE; called to delete the named file(s) from the run.
Permanently deletes a run and all associated data (sessions, results).
formr_api_delete_run(run_name, prompt = TRUE, verbose = TRUE)formr_api_delete_run(run_name, prompt = TRUE, verbose = TRUE)
run_name |
Name of the run to delete. |
prompt |
Logical. If TRUE (default), asks for interactive confirmation;
in a non-interactive session it errors instead of proceeding unattended.
Pass |
verbose |
Logical. If TRUE (default), reports progress via |
Invisibly TRUE (single run) or a named logical vector (multiple
runs) indicating per-run success; FALSE if the user declines the prompt.
Permanently deletes a survey study. Note: The API may prevent deletion if this survey is currently used in an active run.
formr_api_delete_survey(survey_name, prompt = TRUE, verbose = TRUE)formr_api_delete_survey(survey_name, prompt = TRUE, verbose = TRUE)
survey_name |
Name of the survey to delete. |
prompt |
Logical. If TRUE (default), asks for interactive confirmation;
in a non-interactive session it errors instead of proceeding unattended.
Pass |
verbose |
Logical. If TRUE (default), reports progress via |
Invisibly TRUE on success; FALSE if the user declines the prompt.
Fetches raw results. Advanced users can use this if they want completely raw data without any type coercion or processing.
formr_api_fetch_results( run_name = .formr$run_name, surveys = NULL, session_ids = NULL, item_names = NULL, join = FALSE )formr_api_fetch_results( run_name = .formr$run_name, surveys = NULL, session_ids = NULL, item_names = NULL, join = FALSE )
run_name |
Name of the run. Defaults to |
surveys |
Optional character vector of survey names to filter by. |
session_ids |
Optional character vector of session IDs to filter by. |
item_names |
Optional character vector of item names to filter by. |
join |
Logical. If TRUE, joins the results into a single data frame. |
A tibble of survey results, or (when join = FALSE) a named list of tibbles, one per survey.
Returns a data frame of all files uploaded to a specific run, including their public URLs and timestamps.
formr_api_files(run_name, verbose = TRUE)formr_api_files(run_name, verbose = TRUE)
run_name |
Name of the run. |
verbose |
Logical. If TRUE (default), reports progress via |
A data.frame containing: id, name, path, url, created, modified.
Checks if there is a valid, non-expired session. Does NOT verify token validity with the server (use formr_api_session() for that).
formr_api_is_authenticated()formr_api_is_authenticated()
TRUE if authenticated and token not expired, FALSE otherwise.
Invalidates the current access token on the server and clears the local session state.
formr_api_logout(verbose = TRUE)formr_api_logout(verbose = TRUE)
verbose |
Logical. If TRUE (default), reports progress via |
Invisibly TRUE on success (or FALSE if there was no active session); called to revoke the access token on the server and clear the local session.
Pull Project from Server Scaffolds folder structure if missing, then overwrites local files with Server state.
formr_api_pull_project(run_name, dir = NULL, prompt = TRUE, verbose = TRUE)formr_api_pull_project(run_name, dir = NULL, prompt = TRUE, verbose = TRUE)
run_name |
Name of the run. |
dir |
Local directory to scaffold and write into. Defaults to
|
prompt |
Logical. If TRUE (default), asks for confirmation before
overwriting when run interactively (unless |
verbose |
Logical. If TRUE (default), reports progress via |
Invisibly NULL on success (or FALSE if the user declines the overwrite prompt); called for its side effect of scaffolding dir and writing the run's structure, settings, surveys and files from the server.
Uploads local project files (surveys, assets, settings) to the formr server. Optionally monitors the directory for subsequent changes (Watcher mode).
formr_api_push_project( run_name, dir = NULL, watch = FALSE, background = TRUE, interval = 2, verbose = TRUE )formr_api_push_project( run_name, dir = NULL, watch = FALSE, background = TRUE, interval = 2, verbose = TRUE )
run_name |
Name of the run. |
dir |
Local directory to push from. Defaults to |
watch |
Logical. If TRUE, keeps the connection open and uploads changes immediately when files are saved. |
background |
Logical. If TRUE (default), launches watcher as an RStudio Job. |
interval |
Seconds between checks (default 2). |
verbose |
Logical. If TRUE (default), reports progress via |
Invisibly TRUE when the watcher is launched as a background RStudio job; otherwise invisibly NULL. Called for its side effect of uploading the local project in dir to the server (optionally starting a file-watcher).
Apply Type Definitions and Labels
formr_api_recognise(item_list, results)formr_api_recognise(item_list, results)
item_list |
A data frame containing item metadata. |
results |
A data frame containing the raw results. |
The results data.frame with item types applied: POSIXct timestamps and choice items as haven::labelled vectors.
This is the main function for scientists. It fetches data from the API, automatically cleans types (dates/numbers), reverses items, computes scales, and joins everything into one dataframe.
formr_api_results( run_name = .formr$run_name, ..., compute_scales = TRUE, join = TRUE, remove_test_sessions = TRUE, verbose = TRUE )formr_api_results( run_name = .formr$run_name, ..., compute_scales = TRUE, join = TRUE, remove_test_sessions = TRUE, verbose = TRUE )
run_name |
Name of the run. Defaults to |
... |
Filters passed to API (e.g. |
compute_scales |
Logical. Should scales (e.g. |
join |
Logical. If TRUE (default), joins all surveys into one wide dataframe. |
remove_test_sessions |
Logical. Filter out sessions marked as testing? |
verbose |
Logical. Print progress messages? |
A processed tibble with class formr_results.
Reverses numeric items ending in 'R' based on metadata bounds.
Critically, it also updates haven::labelled attributes so that
the text labels point to the new, reversed values.
formr_api_reverse(results, item_list)formr_api_reverse(results, item_list)
results |
A data frame containing the results. |
item_list |
A data frame containing item metadata. |
The results data.frame with reverse-keyed items (those ending in R) flipped and their value labels remapped.
Retrieve the settings for one or more runs as a tidy data frame, or update them by providing a named list of new values.
formr_api_run_settings(run_name, settings = NULL, verbose = TRUE)formr_api_run_settings(run_name, settings = NULL, verbose = TRUE)
run_name |
Name of the run (or a vector of names). |
settings |
A list of settings to update (e.g., |
verbose |
Logical. If TRUE (default), reports progress via |
If settings is NULL: A data.frame/tibble with details for all requested runs.
If settings is provided: Invisibly returns TRUE on success.
Export the current run structure as a list (GET) or replace it by importing a JSON file (PUT).
formr_api_run_structure( run_name, structure_json_path = NULL, file = NULL, verbose = TRUE )formr_api_run_structure( run_name, structure_json_path = NULL, file = NULL, verbose = TRUE )
run_name |
Name of the run. |
structure_json_path |
Optional path to a JSON file to IMPORT (PUT) structure. If provided, the function uploads this file to the server. |
file |
Optional path to save the DOWNLOADED (GET) structure as a .json file. This ensures a perfect 1:1 backup of the server configuration. |
verbose |
Logical. If TRUE (default), reports progress via |
GET (default): A formr_run_structure object (list) for inspection.
GET (file provided): Invisibly returns the file path.
PUT: Invisibly returns TRUE on success.
Returns a data frame of all runs accessible to the user, including status flags and timestamps.
formr_api_runs()formr_api_runs()
A data.frame containing run details: id, name, title, public (bool), cron_active (bool), locked (bool), created (POSIXct), modified (POSIXct).
Returns the current session object or NULL if not authenticated.
formr_api_session()formr_api_session()
A list, or NULL if not authenticated:
base_url: parsed URL (httr style).
token: the bearer access token.
scope: space-delimited string of scopes granted to this
token. NA_character_ when the auth path couldn't introspect
(direct access-token authentication, or older server). ""
means the credential was issued with no scopes — every API call
will 403 until the user picks scopes at admin/account#api.
expires_at: POSIXct of token expiry (or NULL).
Controls the flow of one or more sessions.
formr_api_session_action( run_name, session_codes, action, position = NULL, verbose = TRUE )formr_api_session_action( run_name, session_codes, action, position = NULL, verbose = TRUE )
run_name |
Name of the run. |
session_codes |
A single code or vector of session codes. |
action |
One of: "end_external", "toggle_testing", "move_to_position", "execute", "advance". |
position |
Required only if action is "move_to_position". |
verbose |
Logical. If TRUE (default), reports progress via |
A logical vector indicating success for each session.
Returns a tidy data frame of sessions. Can either list all sessions (with filtering) or fetch specific sessions by their codes.
formr_api_sessions( run_name, session_codes = NULL, active = NULL, testing = NULL, limit = 1000, offset = 0, verbose = TRUE )formr_api_sessions( run_name, session_codes = NULL, active = NULL, testing = NULL, limit = 1000, offset = 0, verbose = TRUE )
run_name |
Name of the run. |
session_codes |
Optional. A character vector of session codes to fetch specific details for.
If provided, |
active |
Filter: TRUE for ongoing, FALSE for finished, NULL for all. |
testing |
Filter: TRUE for test sessions, FALSE for real users, NULL for all. |
limit |
Pagination limit (default 1000). |
offset |
Pagination offset (default 0). |
verbose |
Logical. If TRUE (default), reports progress via |
A combined tibble of session states and details.
Retrieves the item table for a survey. Can return a tibble (JSON) or download the original Excel file (XLSX).
formr_api_survey_structure(survey_name, format = "json", file_path = NULL)formr_api_survey_structure(survey_name, format = "json", file_path = NULL)
survey_name |
The name of the survey. |
format |
The format to retrieve: "json" (default) or "xlsx". |
file_path |
Optional. Required if format is "xlsx". |
In JSON mode (the default) a tibble of the survey's items; in xlsx mode invisibly the file_path written.
Returns a list of all surveys owned by the user.
formr_api_surveys(name_pattern = NULL, verbose = TRUE)formr_api_surveys(name_pattern = NULL, verbose = TRUE)
name_pattern |
Optional. Filter surveys by name (partial match). |
verbose |
Logical. If TRUE (default), reports progress via |
A tibble of surveys (id, name, created, modified, results_table).
Returns information about when the current token expires.
formr_api_token_expiry()formr_api_token_expiry()
A list with:
expires_at: POSIXct of expiry time (or NULL if unknown)
seconds_left: Seconds until expiry (or NA if unknown)
is_expired: TRUE if token has expired
Returns one row per (participant × unit × iteration) for the run — the
history view that complements formr_api_sessions() (which gives one
row per participant with their current unit only).
formr_api_unit_sessions( run_name, session_codes = NULL, testing = NULL, since = NULL, limit = 1000, offset = 0, verbose = TRUE )formr_api_unit_sessions( run_name, session_codes = NULL, testing = NULL, since = NULL, limit = 1000, offset = 0, verbose = TRUE )
run_name |
Name of the run. |
session_codes |
Optional character vector — restrict to one or more participants' histories. |
testing |
Filter: TRUE for test sessions only, FALSE for real participants only, NULL for both. |
since |
Optional ISO 8601 datetime string. Returns only unit
sessions whose |
limit |
Pagination limit (default 1000, max 10000). |
offset |
Pagination offset (default 0). |
verbose |
Logical. If TRUE (default), reports progress via |
Use this for trajectory plots (Sankey, alluvial), drop-off analytics,
and debugging stuck participants. The rows arrive ordered by
(session, created, unit_session_id), so dplyr::group_by(session) |> dplyr::mutate(next_unit = dplyr::lead(unit_description)) gives the
edges of a trajectory plot directly.
Special units (OverviewScriptPage, ServiceMessagePage, ReminderEmail)
surface with position = NA because they live outside the ordered
run flow.
A tidy tibble with columns: unit_session_id, session,
testing, unit_id, unit_type, unit_description, position,
iteration, created, expires, ended, expired, result,
state.
Uploads local file(s) to the run. Accepts a single file path, a vector of file paths, or a directory path (which will upload all files within that directory).
formr_api_upload_file(run_name, path, verbose = TRUE)formr_api_upload_file(run_name, path, verbose = TRUE)
run_name |
Name of the run. |
path |
Local path to the file, a vector of paths, or a directory path. |
verbose |
Logical. If TRUE (default), reports progress via |
Invisibly returns a list of server responses.
Uploads a survey structure.
formr_api_upload_survey( file_path = NULL, google_sheet_url = NULL, verbose = TRUE )formr_api_upload_survey( file_path = NULL, google_sheet_url = NULL, verbose = TRUE )
file_path |
Path to a local file. |
google_sheet_url |
Google Sheet URL. |
verbose |
Logical. If TRUE (default), reports progress via |
Invisibly the server response; called to upload or update a survey from a local file or Google Sheet.
After connecting to formr using formr_connect()
you can backup uploaded files using this command.
formr_backup_files( survey_name, overwrite = FALSE, save_path = NULL, host = formr_last_host() )formr_backup_files( survey_name, overwrite = FALSE, save_path = NULL, host = formr_last_host() )
survey_name |
case-sensitive name of a survey your account owns |
overwrite |
should existing files be overwritten? defaults to FALSE |
save_path |
directory to write the files into. Defaults to a sub-folder
named after the survey inside |
host |
defaults to |
Invisibly the file list with an updated downloaded field; called to
download a survey's user-uploaded files into save_path.
## Not run: # Not run: needs a live formr server and an authenticated session. formr_backup_files(survey_name = 'training_diary', save_path = tempdir() ) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_backup_files(survey_name = 'training_diary', save_path = tempdir() ) ## End(Not run)
Backup a study by downloading all surveys, results, item displays, run shuffle, user overview and user details. This function will save the data in a folder named after the study.
formr_backup_study( study_name, save_path = NULL, host = formr_last_host(), overwrite = FALSE )formr_backup_study( study_name, save_path = NULL, host = formr_last_host(), overwrite = FALSE )
study_name |
case-sensitive name of a study your account owns |
save_path |
directory to write the backup into. Defaults to a sub-folder
named after the study inside |
host |
defaults to |
overwrite |
should existing files be overwritten? |
Invisibly NULL; called for its side effect of downloading a whole study
(run structure, surveys, files and results) into save_path.
## Not run: # Not run: needs a live formr server and an authenticated session. formr_default_dir(tempdir()) formr_backup_study(study_name = 'training_diary' ) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_default_dir(tempdir()) formr_backup_study(study_name = 'training_diary' ) ## End(Not run)
Backup surveys by downloading item lists, results, item displays and file lists.
formr_backup_surveys( survey_names, surveys = list(), save_path = NULL, overwrite = FALSE, host = formr_last_host() )formr_backup_surveys( survey_names, surveys = list(), save_path = NULL, overwrite = FALSE, host = formr_last_host() )
survey_names |
case-sensitive names of surveys your account owns |
surveys |
a list of survey data (from a run structure), optional |
save_path |
directory to write the surveys into. Defaults to
|
overwrite |
should existing files be overwritten? |
host |
defaults to |
Invisibly NULL; called for its side effect of downloading surveys
(items, results, item displays and files) into save_path.
## Not run: # Not run: needs a live formr server and an authenticated session. formr_backup_surveys(survey_names = 'training_diary', save_path = file.path(tempdir(), 'surveys')) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_backup_surveys(survey_names = 'training_diary', save_path = file.path(tempdir(), 'surveys')) ## End(Not run)
Connects to formr using your normal login and the httr library
which supports persistent session cookies. Calling this function will persist
the specified host (by default https://rforms.org) in further formr_ function
calls. You can change this by calling formr_last_host()
formr_connect( email = NULL, password = NULL, host = formr_last_host(), keyring = NULL )formr_connect( email = NULL, password = NULL, host = formr_last_host(), keyring = NULL )
email |
your registered email address |
password |
your password |
host |
defaults to |
keyring |
a shorthand for the account you're using |
Invisibly TRUE on success; called for its side effect of establishing
an authenticated cookie session with the formr server (stored in httr's cookie jar).
## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(keyring = "formr_diary_study_account" ) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(keyring = "formr_diary_study_account" ) ## End(Not run)
formr's file-writing functions (e.g. formr_backup_study(),
formr_api_backup_run(), formr_api_pull_project()) never write to your
working directory by default. Instead they default their destination to the
value stored here, which is unset (NULL) until you choose one — so nothing
is ever written until you opt in. Call this function with a path to set a
session-wide default, or without arguments to read the current value. The
path is held in memory for the current R session only; nothing is written to
disk to persist it. There is no separate reset: the value lasts until you
overwrite it with another path or your R session ends.
formr_default_dir(dir = NULL)formr_default_dir(dir = NULL)
dir |
a single directory path to use as the default. If |
The current default directory as a length-1 character string, or
NULL when none has been set.
formr_default_dir(tempdir()) formr_default_dir()formr_default_dir(tempdir()) formr_default_dir()
Disconnects from formr if connected.
formr_disconnect(host = formr_last_host())formr_disconnect(host = formr_last_host())
host |
defaults to |
Invisibly TRUE on a successful logout; called to log out and clear the active session.
## Not run: # Not run: needs a live formr server and an authenticated session. formr_disconnect() ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_disconnect() ## End(Not run)
Render text
formr_inline_render(text, self_contained = TRUE, ...)formr_inline_render(text, self_contained = TRUE, ...)
text |
that will be written to a tmp file and used as the input argument |
self_contained |
passed to markdown_custom_options |
... |
all other arguments passed to |
A length-1 character string of rendered inline HTML.
After connecting to formr using formr_connect()
you can download detailed times and display counts for each item using this command.
formr_item_displays(survey_name, host = formr_last_host())formr_item_displays(survey_name, host = formr_last_host())
survey_name |
case-sensitive name of a survey your account owns |
host |
defaults to |
A data.frame (parsed JSON) of item-display records with timing and display counts.
## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) formr_item_displays(survey_name = 'training_diary' ) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) formr_item_displays(survey_name = 'training_diary' ) ## End(Not run)
After connecting to formr using formr_connect()
you can download items using this command. One of survey_name or path has to be specified, if both are specified, survey_name is preferred.
formr_items(survey_name = NULL, host = formr_last_host(), path = NULL)formr_items(survey_name = NULL, host = formr_last_host(), path = NULL)
survey_name |
case-sensitive name of a survey your account owns |
host |
defaults to |
path |
path to local JSON copy of the item table |
A list of class formr_item_list (item metadata per item, named by item name).
## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) formr_items(survey_name = 'training_diary' ) ## End(Not run) formr_items(path = system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE))[1:2]## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) formr_items(survey_name = 'training_diary' ) ## End(Not run) formr_items(path = system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE))[1:2]
Render text
formr_knit(text)formr_knit(text)
text |
rmarkdown that will be knit |
A length-1 character string of knitted markdown.
This function returns the default or the last specified host if called without an argument. It changes the host when called with an argument.
formr_last_host(host = NULL)formr_last_host(host = NULL)
host |
defaults to https://rforms.org |
the last specified host
formr_last_host("https://rforms.org") formr_last_host()formr_last_host("https://rforms.org") formr_last_host()
Pulls the run's per-unit interaction history via
formr_api_unit_sessions() and renders a plotly Sankey diagram of
how participants are moving through the ordered units.
formr_overview_sankey( run_name = .formr$run_name, testing = FALSE, orientation = "v", min_avg_visits_to_annotate = 1.1 )formr_overview_sankey( run_name = .formr$run_name, testing = FALSE, orientation = "v", min_avg_visits_to_annotate = 1.1 )
run_name |
Name of the run. Defaults to |
testing |
If |
orientation |
Sankey orientation; |
min_avg_visits_to_annotate |
Threshold above which a node's label gets the "avg N visits" suffix. Default 1.1 – slightly above exactly-once so single-pass runs stay clean. |
Sankey diagrams can only draw acyclic graphs, but diary / longitudinal studies revisit the same units across iterations. To stay readable without losing information, the helper collapses each position to a single node (counting only the first time a participant visits it) and surfaces the average per-participant visit count as an "avg N visits" suffix on the node label. Single-pass runs stay clutter-free (no suffix when the average is ~1); diary studies show e.g. "p20: Daily mood (avg 14.2 visits)" so the loop density is visible without drawing it.
Designed to be called from an OverviewScriptPage on rforms.org, where
the server injects the per-token .formr$access_token / .formr$host
/ .formr$run_name environment and formr_api_authenticate() picks
them up automatically. Outside an Overview render, set
run_name explicitly and call formr_api_authenticate() first.
A plotly Sankey object, or NULL with a message when there
are no rows to plot. Returning NULL lets the caller's knitr chunk
gracefully display the message instead of erroring.
This function chains formr_recognise() and formr_aggregate()
in sequence. Useful if you want to post-process raw results before aggregating etc.
formr_post_process_results( item_list = NULL, results, compute_alphas = FALSE, fallback_max = 5, plot_likert = FALSE, quiet = FALSE, item_displays = NULL, tag_missings = !is.null(item_displays), remove_test_sessions = TRUE )formr_post_process_results( item_list = NULL, results, compute_alphas = FALSE, fallback_max = 5, plot_likert = FALSE, quiet = FALSE, item_displays = NULL, tag_missings = !is.null(item_displays), remove_test_sessions = TRUE )
item_list |
an item_list, defaults to NULL |
results |
survey results |
compute_alphas |
passed to formr_aggregate, defaults to TRUE |
fallback_max |
passed to formr_reverse, defaults to 5 |
plot_likert |
passed to formr_aggregate, defaults to TRUE |
quiet |
passed to formr_aggregate, defaults to FALSE |
item_displays |
an item display table, necessary to tag missings |
tag_missings |
should missings that result from an item not being shown be distinguished from missings due to skipped questions? |
remove_test_sessions |
by default, formr removes results resulting from test session (animal names and null session codes) |
A data.frame/tibble with recognised types, reverse-keyed items flipped, scales aggregated, and missing values tagged.
results = jsonlite::fromJSON(txt = system.file('extdata/BFI_post.json', package = 'formr', mustWork = TRUE)) items = formr_items(path = system.file('extdata/BFI_post_items.json', package = 'formr', mustWork = TRUE)) item_displays = jsonlite::fromJSON( system.file('extdata/BFI_post_itemdisplay.json', package = 'formr', mustWork = TRUE)) processed_results = formr_post_process_results(items, results, item_displays = item_displays, compute_alphas = FALSE, plot_likert = FALSE)results = jsonlite::fromJSON(txt = system.file('extdata/BFI_post.json', package = 'formr', mustWork = TRUE)) items = formr_items(path = system.file('extdata/BFI_post_items.json', package = 'formr', mustWork = TRUE)) item_displays = jsonlite::fromJSON( system.file('extdata/BFI_post_itemdisplay.json', package = 'formr', mustWork = TRUE)) processed_results = formr_post_process_results(items, results, item_displays = item_displays, compute_alphas = FALSE, plot_likert = FALSE)
After connecting to formr using formr_connect()
you can download data using this command.
formr_raw_results(survey_name, host = formr_last_host())formr_raw_results(survey_name, host = formr_last_host())
survey_name |
case-sensitive name of a survey your account owns |
host |
defaults to |
The survey's results before processing: a data.frame (or the raw parsed list).
## Not run: # Not run: needs a live formr server and an authenticated session. formr_raw_results(survey_name = 'training_diary' ) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_raw_results(survey_name = 'training_diary' ) ## End(Not run)
Once you've retrieved an item table using formr_items() you can use this
function to correctly type your variables based on the item table (e.g. formr free text types will be character, but select_add_one will be factor, dates are also typed as Date, datetimes as POSIXct).
formr_recognise( survey_name = NULL, item_list = formr_items(survey_name, host = host), results = formr_raw_results(survey_name, host = host), host = formr_last_host() )formr_recognise( survey_name = NULL, item_list = formr_items(survey_name, host = host), results = formr_raw_results(survey_name, host = host), host = formr_last_host() )
survey_name |
case-sensitive name of a survey your account owns |
item_list |
an item_list, will be auto-retrieved based on survey_name if omitted |
results |
survey results, will be auto-retrieved based on survey_name if omitted |
host |
defaults to |
The results data.frame with POSIXct timestamps and numeric/factor/haven::labelled
columns set according to item types.
results = jsonlite::fromJSON(txt = system.file('extdata/gods_example_results.json', package = 'formr', mustWork = TRUE)) class(results$created) items = formr_items(path = system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE)) results = formr_recognise(item_list = items, results = results) class(results$created)results = jsonlite::fromJSON(txt = system.file('extdata/gods_example_results.json', package = 'formr', mustWork = TRUE)) class(results$created) items = formr_items(path = system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE)) results = formr_recognise(item_list = items, results = results) class(results$created)
Render text
formr_render(text, self_contained = FALSE, ...)formr_render(text, self_contained = FALSE, ...)
text |
that will be written to a tmp file and used as the input argument |
self_contained |
passed to markdown_custom_options |
... |
all other arguments passed to |
A length-1 character string: the path to the rendered HTML file.
Render text
formr_render_commonmark(text)formr_render_commonmark(text)
text |
that will be passed to knitr |
A length-1 character string of HTML rendered from CommonMark.
formr_render_commonmark("There are only `r sample(2:3, 1)` types of people.")formr_render_commonmark("There are only `r sample(2:3, 1)` types of people.")
After connecting to formr using formr_connect()
you can download data and process it. This approach calls the following functions in the right sequence: formr_raw_results()
formr_items(), formr_item_displays() and formr_post_process_results(). So, results are downloaded, metadata on items (labels etc.) is
added, normal and missing values are labelled. In the end, items like bfi_extra_3R are reversed in place (maintaining labels but changing underlying numbers),
and scales are aggregated (bfi_extra_1, bfi_extra_2, bfi_extra_3R become bfi_extra)
formr_results(survey_name, host = formr_last_host(), ...)formr_results(survey_name, host = formr_last_host(), ...)
survey_name |
case-sensitive name of a survey your account owns |
host |
defaults to |
... |
passed to |
A tibble of processed, aggregated survey results (the output of formr_post_process_results()).
## Not run: # Not run: needs a live formr server and an authenticated session. formr_results(survey_name = 'training_diary' ) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_results(survey_name = 'training_diary' ) ## End(Not run)
Example: If your data contains Extraversion_1, Extraversion_2R and Extraversion_3, there will be two new variables in the result: Extraversion_2 (reversed to align with _1 and _2) and Extraversion, the mean score of the three. If you supply an item table, the maximum possible answer to the item will be used to reverse it. If you don't, the maximum actually given answer or the fallback_max argument will be used to reverse it. It's faster to do this without an item table, but this can lead to problems, if you mis-specify the fallback max or the highest possible value does not occur in the data.
formr_reverse(results, item_list = NULL, fallback_max = 5)formr_reverse(results, item_list = NULL, fallback_max = 5)
results |
survey results |
item_list |
an item_list, defaults to NULL |
fallback_max |
defaults to 5 - if the item_list is set to null, we will use this to reverse |
The results data.frame with reverse-keyed (R-suffixed) items flipped and
labelled items' value labels updated.
## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) icar_items = formr_items(survey_name='ICAR',host = 'http://localhost:8888/formr/') # get some simulated data and aggregate it sim_results = formr_simulate_from_items(icar_items) reversed_items = formr_reverse(item_list = icar_items, results = sim_results) ## End(Not run) results = jsonlite::fromJSON(txt = system.file('extdata/gods_example_results.json', package = 'formr', mustWork = TRUE)) items = formr_items(path = system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE)) formr_reverse(results, items)## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) icar_items = formr_items(survey_name='ICAR',host = 'http://localhost:8888/formr/') # get some simulated data and aggregate it sim_results = formr_simulate_from_items(icar_items) reversed_items = formr_reverse(item_list = icar_items, results = sim_results) ## End(Not run) results = jsonlite::fromJSON(txt = system.file('extdata/gods_example_results.json', package = 'formr', mustWork = TRUE)) items = formr_items(path = system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE)) formr_reverse(results, items)
After connecting to formr using formr_connect()
you can download the study/run structure using this command.
formr_run_structure(run_name, host = formr_last_host())formr_run_structure(run_name, host = formr_last_host())
run_name |
case-sensitive name of a run your account owns |
host |
defaults to |
A list (parsed JSON) describing the run structure (its units).
## Not run: # Not run: needs a live formr server and an authenticated session. formr_run_structure(run_name = 'training_diary' ) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_run_structure(run_name = 'training_diary' ) ## End(Not run)
formr has a specific module for randomisation.
After connecting using formr_connect()
you can download the assigned random groups and merge them with your data.
formr_shuffled(run_name, host = formr_last_host())formr_shuffled(run_name, host = formr_last_host())
run_name |
case-sensitive name of the run in which you randomised participants |
host |
defaults to |
A data.frame (parsed JSON) of random group assignments keyed by session.
## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) formr_shuffled(run_name = 'different_drills' ) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) formr_shuffled(run_name = 'different_drills' ) ## End(Not run)
Once you've retrieved an item table using formr_items() you can use this
function to sample data from the possible choices.
At the moment random data is only generated for choice-type
items and numeric ones, as these are most likely to enter data analysis.
Does not yet handle dates, times, text, locations, colors
formr_simulate_from_items(item_list, n = 300)formr_simulate_from_items(item_list, n = 300)
item_list |
the result of a call to |
n |
defaults to 300 |
A data.frame of simulated survey data (columns id, created, modified,
ended, plus sampled values for each item).
## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) sim = formr_simulate_from_items(item_list = formr_items('training_diary'), n = 100) summary(lm(pushups ~ pullups, data = sim)) ## End(Not run) items = formr_items(path = system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE)) fakedata = formr_simulate_from_items(items, n = 20) fakedata[1:2,]## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) sim = formr_simulate_from_items(item_list = formr_items('training_diary'), n = 100) summary(lm(pushups ~ pullups, data = sim)) ## End(Not run) items = formr_items(path = system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE)) fakedata = formr_simulate_from_items(items, n = 20) fakedata[1:2,]
Securely stores formr credentials in the system keyring. This function supports two modes:
Classic Mode: Stores email/password (and optional 2FA) for a specific account name.
API Mode: Stores OAuth credentials or Access Tokens for a specific host.
formr_store_keys( account_name = NULL, email = NULL, password = NULL, secret_2fa = NULL, host = "https://rforms.org", client_id = NULL, client_secret = NULL, access_token = NULL, account = NULL, verbose = TRUE )formr_store_keys( account_name = NULL, email = NULL, password = NULL, secret_2fa = NULL, host = "https://rforms.org", client_id = NULL, client_secret = NULL, access_token = NULL, account = NULL, verbose = TRUE )
account_name |
(Classic) A shorthand name for the account. If provided, Classic mode is triggered. |
email |
(Classic) Email address for the account. Will be prompted if omitted. |
password |
(Classic) Optional. Provide to skip interactive prompt (useful for scripts/tests). |
secret_2fa |
(Classic) A 2FA secret. Set to NULL to be prompted, or "" if not used. |
host |
(API) The API URL (e.g., https://rforms.org). Defaults to rforms.org. |
client_id |
(API) OAuth Client ID. |
client_secret |
(API) OAuth Client Secret. |
access_token |
(API) Direct Personal Access Token (alternative to OAuth). |
account |
(API) Optional string identifier for multiple accounts on the same host. |
verbose |
Logical. If TRUE (default), reports progress via |
Invisibly NULL; called for its side effect of storing the password and 2FA seed in the system keyring.
## Not run: # Not run: prompts interactively and writes to the system keyring. # --- Classic EXAMPLES --- # Prompts for password interactively formr_store_keys("formr_diary_study_account") # --- NEW API EXAMPLES --- # Store OAuth Credentials for a custom host formr_store_keys(host = "http://localhost", client_id = "my-id", client_secret = "my-secret") # Store token for a specific secondary account formr_store_keys(host = "http://localhost", client_id = "my-id", client_secret = "my-secret", account = "project_b") ## End(Not run)## Not run: # Not run: prompts interactively and writes to the system keyring. # --- Classic EXAMPLES --- # Prompts for password interactively formr_store_keys("formr_diary_study_account") # --- NEW API EXAMPLES --- # Store OAuth Credentials for a custom host formr_store_keys(host = "http://localhost", client_id = "my-id", client_secret = "my-secret") # Store token for a specific secondary account formr_store_keys(host = "http://localhost", client_id = "my-id", client_secret = "my-secret", account = "project_b") ## End(Not run)
To automatically create surveys using formr, you can upload survey item tables from R. Only file uploads are available. The file name determines the survey name. Updating existing surveys is not implemented and not recommended (because of the sanity checks we require to prevent data deletion).
formr_upload_items(survey_file_path, host = formr_last_host())formr_upload_items(survey_file_path, host = formr_last_host())
survey_file_path |
the path to an item table in csv/json/xlsx etc. |
host |
defaults to |
Invisibly TRUE on success; called to upload an item-table file to the formr server.
## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) items <- system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE) formr_upload_items(items) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) items <- system.file('extdata/gods_example_items.json', package = 'formr', mustWork = TRUE) formr_upload_items(items) ## End(Not run)
After connecting to formr using formr_connect()
you can download uploaded files using this command.
formr_uploaded_files(survey_name, host = formr_last_host())formr_uploaded_files(survey_name, host = formr_last_host())
survey_name |
case-sensitive name of a survey your account owns |
host |
defaults to |
A list (parsed JSON) of uploaded-file metadata.
## Not run: # Not run: needs a live formr server and an authenticated session. formr_uploaded_files(survey_name = 'training_diary' ) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_uploaded_files(survey_name = 'training_diary' ) ## End(Not run)
formr collects information about users' progression through the run
After connecting using formr_connect()
you can download a table showing their progression through the run.
formr_user_detail(run_name, host = formr_last_host())formr_user_detail(run_name, host = formr_last_host())
run_name |
case-sensitive name of the run in which you randomised participants |
host |
defaults to |
A data.frame (parsed JSON) of detailed per-session progress through the run.
## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) formr_user_detail(run_name = 'different_drills' ) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) formr_user_detail(run_name = 'different_drills' ) ## End(Not run)
formr collects information about users' progression through the run
After connecting using formr_connect()
you can download a table showing where they are in the run.
formr_user_overview(run_name, host = formr_last_host())formr_user_overview(run_name, host = formr_last_host())
run_name |
case-sensitive name of the run in which you randomised participants |
host |
defaults to |
A data.frame (parsed JSON) of per-session progress/overview data.
## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) formr_user_overview(run_name = 'different_drills' ) ## End(Not run)## Not run: # Not run: needs a live formr server and an authenticated session. formr_connect(email = '[email protected]', password = 'zebrafinch' ) formr_user_overview(run_name = 'different_drills' ) ## End(Not run)
useful to programmatically access openCPU session object stored in character variables etc.
get_opencpu_rds(session_url, local = TRUE)get_opencpu_rds(session_url, local = TRUE)
session_url |
the session url, e.g. https://public.opencpu.org/ocpu/tmp/x02a93ec/R/.val/rds |
local |
defaults to FALSE, if true, will assume that the session is not on another server, and do some not-very-smart substitution to load it via the file system instead of HTTP/HTTPS |
The R object deserialised from an OpenCPU session's RDS result (or loaded from a local .RData).
## Not run: # Not run: fetches a result from a remote OpenCPU server. get_opencpu_rds('https://public.opencpu.org/ocpu/tmp/x02a93ec/R/.val/rds') ## End(Not run)## Not run: # Not run: fetches a result from a remote OpenCPU server. get_opencpu_rds('https://public.opencpu.org/ocpu/tmp/x02a93ec/R/.val/rds') ## End(Not run)
Often, you want to substitute missing values with some implicit known value (e.g. if the question on number of sexual partners was skipped for sexually inactive people, you know the missing should turn into zero)
if_na(x, missing)if_na(x, missing)
x |
the variable |
missing |
What to replace missing values with |
x with its NA values replaced by missing.
number_of_sex_partners <- c(1, 3, 5, 10, NA, 29) if_na(number_of_sex_partners, 0)number_of_sex_partners <- c(1, 3, 5, 10, NA, 29) if_na(number_of_sex_partners, 0)
This function makes sure you know what to expect when evaluating uncertain results in an if-clause. In most cases, you should not use this function, because it can lump a lot of very different cases together, but it may have some use for fool-proofing certain if-clauses on rforms.org, where a field in a survey may either not exist, be missing or have a value to check.
if_na_null(test, na = FALSE, null = FALSE)if_na_null(test, na = FALSE, null = FALSE)
test |
condition. can only have length 0 or length 1 |
na |
returned if the condition has a missing value |
null |
passed to ifelse |
A length-0-or-1 value: test when it is non-missing, na when test
is NA, or null when test has length 0.
testdf = data.frame(test1 = 1, test2 = NA) if ( if_na_null(testdf$test1 == 1) ) { print("go on") } if ( if_na_null(testdf$test2 == 1) ) { print("not shown") } if ( if_na_null(testdf$test3 == 1) ) { print("not shown") } tryCatch({ if ( if_na_null(testdf2$test1 == 1) ) { print("causes error") } }, error = function(e) { warning(e) })testdf = data.frame(test1 = 1, test2 = NA) if ( if_na_null(testdf$test1 == 1) ) { print("go on") } if ( if_na_null(testdf$test2 == 1) ) { print("not shown") } if ( if_na_null(testdf$test3 == 1) ) { print("not shown") } tryCatch({ if ( if_na_null(testdf2$test1 == 1) ) { print("causes error") } }, error = function(e) { warning(e) })
ifelse(), but allows you to assign a third value to missings.Deprecated. Please use dplyr::if_else() in the future.
Defaults to assigning the "no" value to missing values as well. Often missings encapsulate
some sort of meaning for the variable you're trying to define.
ifelsena(test, yes, no, missing = no)ifelsena(test, yes, no, missing = no)
test |
passed to ifelse |
yes |
passed to ifelse |
no |
passed to ifelse |
missing |
defaults to the value for no |
A vector like ifelse()'s result, with NA positions replaced by missing.
## Not run: # Not run: ifelsena() is deprecated; use dplyr::if_else() instead. data(beavers) beaver1$activ[1:10] = NA beaver1$hyperactive = ifelse(beaver1$activ > 1, 1, 0) table(beaver1$hyperactive) beaver1$hyperactive = ifelsena(beaver1$activ > 1, 1, 0) table(beaver1$hyperactive) ## End(Not run)## Not run: # Not run: ifelsena() is deprecated; use dplyr::if_else() instead. data(beavers) beaver1$activ[1:10] = NA beaver1$hyperactive = ifelse(beaver1$activ > 1, 1, 0) table(beaver1$hyperactive) beaver1$hyperactive = ifelsena(beaver1$activ > 1, 1, 0) table(beaver1$hyperactive) ## End(Not run)
supply min,max as POSIXct
in_time_window(min, max)in_time_window(min, max)
min |
POSIXct < max |
max |
POSIXct > min |
A length-1 logical: TRUE if the current time lies between min and max.
in_time_window(Sys.time() - 1, Sys.time() + 1)in_time_window(Sys.time() - 1, Sys.time() + 1)
Shortcut for attributes(survey$item_name)$item. Fails with a warning.
item(survey, item_name)item(survey, item_name)
survey |
survey with item_list attribute |
item_name |
item name |
The metadata list for a single item (from a survey variable's attributes),
or NULL with a warning if not found.
example(formr_post_process_results) item(processed_results, "BFIK_extra_4")example(formr_post_process_results) item(processed_results, "BFIK_extra_4")
get item list from survey attributes
items(survey)items(survey)
survey |
survey with item_list attribute |
A list of class formr_item_list extracted from a survey data.frame's variable attributes.
example(formr_post_process_results) items(processed_results)[[1]]example(formr_post_process_results) items(processed_results)[[1]]
Knit using knitr, but prefix file name to figure and cache folder (to knit in parallel on e.g. a cluster)
knit_prefixed(input, ...)knit_prefixed(input, ...)
input |
input document |
... |
all arguments passed to |
A length-1 character string of knitted output, with figure/cache paths prefixed by the input file name.
Just a simple shorthand to get the last, non-missing argument per default.
Can give more than one element and can include missing elements.
The inverse of first().
last(x, n = 1, na.rm = TRUE)last(x, n = 1, na.rm = TRUE)
x |
vector of which you want the last element |
n |
number of elements to take from the end |
na.rm |
whether to remove missings first, defaults to TRUE |
A vector of the same type as x holding its last n elements
(after dropping NAs when na.rm = TRUE); an empty vector if none remain.
last( c(1:10,NA) ) last( c(1:10,NA), 2, TRUE )last( c(1:10,NA) ) last( c(1:10,NA), 2, TRUE )
custom markdown options for rmarkdown's pandoc
markdown_custom_options( add_to_format = c("+autolink_bare_uris", "+ascii_identifiers", "+tex_math_single_backslash", "-implicit_figures"), fragment.only = FALSE, section_divs = TRUE, break_on_error = FALSE, ... )markdown_custom_options( add_to_format = c("+autolink_bare_uris", "+ascii_identifiers", "+tex_math_single_backslash", "-implicit_figures"), fragment.only = FALSE, section_divs = TRUE, break_on_error = FALSE, ... )
add_to_format |
add these arguments to the default specification |
fragment.only |
whether to get only a html fragment |
section_divs |
whether to disable –section-divs (headings generate section including everything up to the next same-or-higher-level heading) |
break_on_error |
should an error in the R code execution interrupt the rendering or should rendering continue, defaults to FALSE |
... |
all other arguments passed to Custom rmarkdown input format options based on the standard |
An rmarkdown output_format object (from rmarkdown::html_document()/html_fragment()) with customised pandoc/knitr options.
Custom template with github-flavoured markdown based on the standard rmarkdown::html_document(). Adds +pipe_tables, +raw_html, +tex_math_single_backslash, +fenced_code_blocks, +auto_identifiers, +ascii_identifiers, +backtick_code_blocks, +autolink_bare_uris, +intraword_underscores, +strikeout, +hard_line_breaks over markdown_strict. A number of pandoc features are disabled (see markdown_custom_options()), but +yaml_metadata_block is re-enabled, so that it is possible to specify this output function using YAML.
markdown_github(fragment.only = FALSE, break_on_error = FALSE, ...)markdown_github(fragment.only = FALSE, break_on_error = FALSE, ...)
fragment.only |
whether to get only a html fragment |
break_on_error |
should an error in the R code execution interrupt the rendering or should rendering continue, defaults to FALSE |
... |
all other arguments passed to |
An rmarkdown output_format object configured for GitHub-flavoured markdown.
Custom rmarkdown template based on the standard rmarkdown::html_document(), but with hard line breaks. Will add the pandoc '+hard_line_breaks' argument if the origin format is markdown.
markdown_hard_line_breaks(...)markdown_hard_line_breaks(...)
... |
all other arguments passed to |
An rmarkdown output_format object with hard line breaks enabled.
a simple utility functions to avoid that looped Skip Backwards/Skip Forwards in formr are true repeatedly.
next_day(date = NULL)next_day(date = NULL)
date |
defaults to .formr$last_action_date, a hidden variable that is automatically set by rforms.org. Will be coerced to POSIXct. |
A POSIXct: midnight at the start of the day after date.
next_day(Sys.time())next_day(Sys.time())
Helper function for knit_asis objects, useful when e.g. asis_knit_child() was used in a loop.
paste.knit_asis(..., sep = "\n\n\n", collapse = "\n\n\n")paste.knit_asis(..., sep = "\n\n\n", collapse = "\n\n\n")
... |
passed to |
sep |
defaults to two empty lines, passed to |
collapse |
defaults to two empty lines, passed to |
Works like paste() with both the sep and the collapse argument set to two empty lines
A length-1 character string of class knit_asis (the inputs concatenated).
paste.knit_asis("# Headline 1", "## Headline 2")paste.knit_asis("# Headline 1", "## Headline 2")
Print method for formr run structure
## S3 method for class 'formr_api_run_structure' print(x, ...)## S3 method for class 'formr_api_run_structure' print(x, ...)
x |
The object. |
... |
Additional arguments. |
Invisibly returns x; called for its side effect of printing a formatted table of the run's units.
Print new lines in knit_asis outputs
## S3 method for class 'knit_asis' print(x, ...)## S3 method for class 'knit_asis' print(x, ...)
x |
the knit_asis object |
... |
ignored |
Invisibly NULL; called for its side effect of printing the knit_asis content.
Pass in a data.frame with z-standardised values (x - Mean)/SD, and variable names, get a bar chart. Getting your data.frame into this shape probably will mean using tidyr and dplyr If the data.frame has an se column or ymax/ymin columns, these will be displayed on top of the bars and the bars will become transparent.
qplot_on_bar( normed_data, ylab = "Your value", xlab = "Trait", title = "", y_ticks = c("--", "-", "0", "+", "++") )qplot_on_bar( normed_data, ylab = "Your value", xlab = "Trait", title = "", y_ticks = c("--", "-", "0", "+", "++") )
normed_data |
a dataset with a value column containing z-standardised value and a variable column containing labels for those values |
ylab |
Y-axis label, defaults to "Percentage of other people with this value" |
xlab |
X-axis label, empty by default, useful for labeling the plotted trait |
title |
Plot title |
y_ticks |
the ticks labels for -2,1,0,1 and 2 SDs around the mean, default to minuses, pluses and the average sign |
A ggplot object: a bar chart, optionally with error bars.
normed_data = data.frame(variable = c("Extraversion","Openness", "Agreeableness","Neuroticism","Conscientiousness"), value = c(-3,1,-1,0.5,2)) # standardise value qplot_on_bar(normed_data, title = "Your personality") normed_data = data.frame(variable = c("Extraversion","Openness", "Agreeableness","Neuroticism","Conscientiousness"), value = c(-3,1,-1,0.5,2), se = c(0.2,0.3,0.2,0.25,0.4)) # standardise value qplot_on_bar(normed_data, title = "Your personality")normed_data = data.frame(variable = c("Extraversion","Openness", "Agreeableness","Neuroticism","Conscientiousness"), value = c(-3,1,-1,0.5,2)) # standardise value qplot_on_bar(normed_data, title = "Your personality") normed_data = data.frame(variable = c("Extraversion","Openness", "Agreeableness","Neuroticism","Conscientiousness"), value = c(-3,1,-1,0.5,2), se = c(0.2,0.3,0.2,0.25,0.4)) # standardise value qplot_on_bar(normed_data, title = "Your personality")
Pass in a z-standardised value (x - Mean)/SD, get a standard normal distribution.
qplot_on_normal( normed_value, ylab = "Percentage of other people with this value", xlab = "", colour = "blue", x_ticks = c("--", "-", "0", "+", "++") )qplot_on_normal( normed_value, ylab = "Percentage of other people with this value", xlab = "", colour = "blue", x_ticks = c("--", "-", "0", "+", "++") )
normed_value |
a z-standardised value |
ylab |
Y-axis label, defaults to "Percentage of other people with this value" |
xlab |
X-axis label, empty by default, useful for labeling the plotted trait |
colour |
defaults to blue |
x_ticks |
the ticks labels for -2,1,0,1 and 2 SDs around the mean, default to minuses, pluses and the average sign |
A ggplot object showing the standard normal distribution with a reference line at normed_value.
normed_value = scale(x = 20, center = 14, scale = 5) # standardise value qplot_on_normal(normed_value, xlab = "Extraversion")normed_value = scale(x = 20, center = 14, scale = 5) # standardise value qplot_on_normal(normed_value, xlab = "Extraversion")
Pass in a data.frame with z-standardised values (x - Mean)/SD, and variable names, get a bar chart. Getting your data.frame into this shape probably will mean using tidyr + dplyr. If the data.frame has an se column or ymax/ymin columns, these will be displayed on top of the bars and the bars will become transparent.
qplot_on_polar(normed_data, ylab = "Your value", title = "")qplot_on_polar(normed_data, ylab = "Your value", title = "")
normed_data |
a dataset with a value column containing z-standardised value and a variable column containing labels for those values |
ylab |
Y-axis label, defaults to "Percentage of other people with this value" |
title |
Plot title |
A ggplot object drawn in polar coordinates.
weekdays = c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday") normed_data = data.frame(variable = factor(weekdays, weekdays), value = c(0,1,0.2,0.5,1.5,2,1)) # standardise value qplot_on_polar(normed_data, title = "Your alcohol consumption across the week") normed_data = data.frame(variable = factor(1:24,1:24), value = 3+rnorm(24), se = rep(0.2,24)) # standardise value qplot_on_polar(normed_data, title = "Your mood around the clock")weekdays = c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday") normed_data = data.frame(variable = factor(weekdays, weekdays), value = c(0,1,0.2,0.5,1.5,2,1)) # standardise value qplot_on_polar(normed_data, title = "Your alcohol consumption across the week") normed_data = data.frame(variable = factor(1:24,1:24), value = 3+rnorm(24), se = rep(0.2,24)) # standardise value qplot_on_polar(normed_data, title = "Your mood around the clock")
taken from Dirk Eddelbuettel's answer here https://stackoverflow.com/a/14721124/263054.
random_date_in_range(N, lower = "2012/01/01", upper = "2012/12/31")random_date_in_range(N, lower = "2012/01/01", upper = "2012/12/31")
N |
desired number of random dates |
lower |
lower limit |
upper |
upper limit |
A POSIXct vector of N random dates within the given range.
Render text
render_text(text, ...)render_text(text, ...)
text |
that will be written to a tmp file and used as the input argument |
... |
all other arguments passed to |
A length-1 character string of rendered HTML.
Taken from codebook
You can use this function if some of your items have lost their attributes during wrangling
Variables have to have the same name (Duh) and no attributes should be overwritten.
But use with care. Similar to labelled::copy_labels().
rescue_attributes(df_no_attributes, df_with_attributes)rescue_attributes(df_no_attributes, df_with_attributes)
df_no_attributes |
the data frame with missing attributes |
df_with_attributes |
the data frame from which you want to restore attributes |
A data.frame: df with variable attributes restored from a reference data.frame.
Taken from codebook package
reverse the underlying values for a numeric haven::labelled() vector while keeping the labels correct
reverse_labelled_values(x)reverse_labelled_values(x)
x |
a labelled vector |
return the labelled vector with the underlying values having been reversed
x <- haven::labelled(rep(1:3, each = 3), c(Bad = 1, Good = 5)) x reverse_labelled_values(x)x <- haven::labelled(rep(1:3, each = 3), c(Bad = 1, Good = 5)) x reverse_labelled_values(x)
Prints a human-readable audit trail of all data cleaning steps.
## S3 method for class 'formr_results' summary(object, ...)## S3 method for class 'formr_results' summary(object, ...)
object |
A |
... |
Additional arguments passed to summary (ignored). |
Invisibly NULL; called for its side effect of printing the processing audit trail.
Connects to Clickatell using your token and sends a text message.
text_message_clickatell(To, Body, Token, return_result = FALSE)text_message_clickatell(To, Body, Token, return_result = FALSE)
To |
the number you're texting to (usually without zeroes at the beginning) |
Body |
the text message body/text |
Token |
your Clickatell token |
return_result |
whether to return simply TRUE/FALSE on success/failure or the whole result |
Logical TRUE/FALSE indicating send success, or (when return_result = TRUE) the raw API response list.
## Not run: # Not run: sends a real SMS via the Clickatell gateway (needs an account). text_message_clickatell( To = '492222', Body = 'Hello friend', Token = 'Tokentokentoken') ## End(Not run)## Not run: # Not run: sends a real SMS via the Clickatell gateway (needs an account). text_message_clickatell( To = '492222', Body = 'Hello friend', Token = 'Tokentokentoken') ## End(Not run)
Connects to Massenversand.de using your token and sends a text message.
text_message_massenversand( To, From, Body, id, pw, time = "0", msgtype = "t", tarif = "OA", test = "0", return_result = FALSE )text_message_massenversand( To, From, Body, id, pw, time = "0", msgtype = "t", tarif = "OA", test = "0", return_result = FALSE )
To |
the number you're texting to (usually without zeroes at the beginning) |
From |
the number you're texting from |
Body |
the text message body/text |
id |
your Massenversand ID |
pw |
your Massenversand password |
time |
see provider API (defaults to immediate sending) |
msgtype |
see provider API |
tarif |
see provider API |
test |
see provider API |
return_result |
whether to return simply TRUE/FALSE on success/failure or the whole result |
Logical TRUE/FALSE indicating send success (or the raw character API response).
## Not run: # Not run: sends a real SMS via the massenversand.de gateway (needs an account). text_message_massenversand( To = '492222', From = '15005000', Body = 'Hello friend', id = 'ID', pw = 'Tokentokentoken') ## End(Not run)## Not run: # Not run: sends a real SMS via the massenversand.de gateway (needs an account). text_message_massenversand( To = '492222', From = '15005000', Body = 'Hello friend', id = 'ID', pw = 'Tokentokentoken') ## End(Not run)
Connects to Twilio using your token and sends a text message.
text_message_twilio(To, From, Body, Account, Token, return_result = FALSE)text_message_twilio(To, From, Body, Account, Token, return_result = FALSE)
To |
the number you're texting to (usually without zeroes at the beginning) |
From |
the number you're texting from |
Body |
the text message body/text |
Account |
your Twilio account ID |
Token |
your Twilio token |
return_result |
whether to return simply TRUE/FALSE on success/failure or the whole result |
Logical TRUE/FALSE indicating send success, or (when return_result = TRUE) the raw API response list.
## Not run: # Not run: sends a real SMS via the Twilio gateway (needs an account). text_message_twilio( To = '492222', From = '15005000', Body = 'Hello friend', Account = 'ID', Token = 'Tokentokentoken') ## End(Not run)## Not run: # Not run: sends a real SMS via the Twilio gateway (needs an account). text_message_twilio( To = '492222', From = '15005000', Body = 'Hello friend', Account = 'ID', Token = 'Tokentokentoken') ## End(Not run)
checks how much time has passed. You can choose the unit. Implemented via lubridate::dseconds(), not periods, i.e. a minute has 60 seconds, an hour 60 minutes, a day 24 hours. Months and years are not well-defined durations, but we offer them anyway for convenience. Returns true or false.
time_passed( years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0, time = NULL )time_passed( years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0, time = NULL )
years |
365 days |
months |
30 days |
weeks |
7 days |
days |
24 hours |
hours |
60 minutes |
minutes |
60 seconds |
seconds |
argument to |
time |
defaults to .formr$last_action_time, a hidden variable that is automatically set by rforms.org |
A length-1 logical: TRUE if at least the specified duration has elapsed since time.
time_passed(hours = 7, time = Sys.time())time_passed(hours = 7, time = Sys.time())
Exactly like rmarkdown::word_document(), but with one added argument
word_document(..., break_on_error = FALSE)word_document(..., break_on_error = FALSE)
... |
all other arguments passed to |
break_on_error |
should an error in the R code execution interrupt the rendering or should rendering continue, defaults to FALSE |
An rmarkdown output_format object like rmarkdown::word_document(), with an added option not to break on error.