| Type: | Package |
| Title: | 'REDCap' Data Management |
| Version: | 1.1.0 |
| Maintainer: | João Carmezim <jcarmezim@igtp.cat> |
| Description: | REDCap Data Management - 'REDCap' (Research Electronic Data CAPture; https://projectredcap.org) is a web application developed at Vanderbilt University, designed for creating and managing online surveys and databases and the REDCap API is an interface that allows external applications to connect to REDCap remotely, and is used to programmatically retrieve or modify project data or settings within REDCap, such as importing or exporting data. REDCapDM is an R package that allows users to manage data exported directly from REDCap or using an API connection. This package includes several functions designed for pre-processing data, generating reports of queries such as outliers or missing values, and following up on previously identified queries. |
| License: | MIT + file LICENSE |
| URL: | https://bruigtp.github.io/REDCapDM/, https://doi.org/10.1186/s12874-024-02178-6 |
| BugReports: | https://github.com/bruigtp/REDCapDM/issues |
| Encoding: | UTF-8 |
| Imports: | dplyr (≥ 1.1.0), janitor, purrr, rlang (≥ 1.0.0), stringr, tibble, tidyr, tidyselect, labelled, utils, stringi, cli (≥ 3.4.0), forcats, lifecycle, magrittr, lubridate, knitr |
| Suggests: | kableExtra, rmarkdown, testthat (≥ 3.0.0), mockery, ggplot2, openxlsx, readr, REDCapR (≥ 1.2.0), withr |
| VignetteBuilder: | knitr |
| Depends: | R (≥ 4.1) |
| LazyData: | true |
| Config/testthat/edition: | 3 |
| Config/Needs/website: | rmarkdown |
| Config/roxygen2/version: | 8.1.1 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-27 08:37:10 UTC; jcarmezim |
| Author: | João Carmezim [aut, cre], Pau Satorra [aut], Judith Peñafiel [aut], Esther García [aut], Natàlia Pallarès [aut], Cristian Tebé [aut], Ferran Perez Sanchez [ctb] |
| Repository: | CRAN |
| Date/Publication: | 2026-11-27 09:00:02 UTC |
Managing REDCap Data: The R package REDCapDM / REDCapDM: A Toolkit for Managing REDCap Data in R
Description
The REDCapDM package provides tools to import, process, and manage REDCap data within R. It supports data retrieval through the REDCap API or directly from exported files and includes a robust set of functions for data transformation, validation, and discrepancy management. Designed for efficient workflow integration, REDCapDM simplifies the handling of REDCap datasets, making it easier to ensure data quality and consistency.
Key Features:
-
Flexible Data Import: Import data directly from REDCap using API connections or process exported REDCap files.
-
Data Transformation: Streamline the cleaning and preparation of raw datasets for analysis.
-
Query Management: Identify and track data discrepancies, missing events, and manage resolution reports.
Core Functions:
-
redcap_data: Reads data exported from REDCap or retrieved through the REDCap API into R. -
rd_transform: One-step pipeline to clean and preprocess the raw REDCap data.-
rd_dates: Standardize date and datetime fields. -
rd_delete_vars: Remove specified variables (by name or pattern). -
rd_recalculate: Recompute calculated fields and compare with REDCap values. -
rd_factor: Replace numeric multiple-choice columns with their factor version. -
rd_checkbox: Expand checkbox responses with custom labels and rename 'var___1' columns (REDCap style) to 'var_option'. -
rd_split: Splits a REDCap dataset by form or event. -
rd_insert_na: Manually set specified variables to missing based on a logical filter. -
rd_rlogic: Translate REDCap branching or calculation logic into R syntax. -
rd_dictionary: Update dictionary (translation of REDCap logic into R syntax) to reflect transformed data and logic.
-
-
rd_query: Identifies discrepancies (queries) in the dataset for validation. -
rd_event: Detects missing events in longitudinal datasets. -
check_queries: Compares historical and current query reports to track changes and additions. -
rd_export: Exports a summary report of identified queries to an Excel (.xlsx) file.
Package options
-
REDCapDM.quiet: setoptions(REDCapDM.quiet = TRUE)to hide the informative messages of the package (e.g. the progress ofrd_transform()). Errors and warnings are always shown.
Errors and warnings
The errors, warnings and messages of the package have the classes REDCapDM_error, REDCapDM_warning and
REDCapDM_message, so they can be handled programmatically, e.g.
tryCatch(rd_query(...), REDCapDM_error = function(e) ...). Errors caused by a wrong argument value also have the
class REDCapDM_error_argument.
Examples
## Not run:
# Install REDCapDM from CRAN:
install.packages("REDCapDM")
# Install the latest version of REDCapDM from GitHub:
remotes::install_github("bruigtp/REDCapDM")
## End(Not run)
Check for Changes Between Two Query Reports
Description
Compare an older query report (old) with a newer one (new) and classify each
query into one of four statuses:
-
Pending — the same query is present in both reports (no change detected),
-
Solved — the query was present in the old report but is absent from the new report,
-
New — the query appears in the new report but was not present in the old report,
-
Miscorrected — a special case where a query in the new report is marked as
Newbut the old report has a query with the sameIdentifier,Event,RepetitionandField(each of them when both reports have it;Descriptionwhen they don't haveField), suggesting a re-issued or modified query for the same record and field.
The function returns a detailed comparison table of queries with a Modification factor (one of the four statuses) and an HTML summary table showing counts per status.
Usage
check_queries(old, new, report_title = NULL, return_viewer = TRUE)
Arguments
old |
Data frame containing the previous (older) query report. Must include |
new |
Data frame containing the newer query report. Must include |
report_title |
Optional single string used as the caption for the HTML summary table. With |
return_viewer |
Logical; if |
Details
Requirements:
Both
oldandnewmust be data frames.Both data frames must contain at least the following columns:
Identifier(text, factor or number),Description, andQuery.Every query must have an
Identifier(the record identifier of the data).A
Codecolumn is optional; the codes ofoldare used to sort the queries, and the codes of the result are assigned again (see the value). IfCodeexists innew, it is removed at the beginning of the routine to avoid conflicts with re-assigned codes.
The function merges the two reports, constructs composite keys used for comparison, classifies each row into a modification state, detects and re-labels Miscorrected cases, reassigns a Code per Identifier to keep codes consistent, and returns a detailed dataset plus an optional HTML summary viewer.
Value
A list of class REDCapDM_report, which prints a short summary (see print.REDCapDM_report()), with two elements:
queriesA data frame containing all queries present in either
oldornew. A factor columnModificationindicates the state for each row (levels:Pending,Solved,Miscorrected,New). The function also reassignsCodevalues so codes are consistent perIdentifier: a code is the number of each query of its record in this result, not a permanent identifier of the query (the same query can have another code in another comparison).resultsIf
return_viewer = TRUE, an HTMLknitr::kable(styled withkableExtra) summarising totals per state. Ifreturn_viewer = FALSE, this isNULL.
Notes and edge cases
-
Column types: If
Identifier,DescriptionorQueryare factors, they will be used in the comparison — it is recommended to convert them to character prior to callingcheck_queries()to avoid factor-level mismatches. -
Sorting: The rows are sorted by
Identifierin natural order (e.g."100-2"before"100-10").Identifieris returned as a number only when every identifier is a plain number without leading zeros (e.g."007"is kept as text). -
Identity of a query: a query is the same in both reports when it has the same
Identifier,EventandRepetition(when both reports have them),Field(when both reports have it; otherwiseDescription) andQuery.Eventis the unique event name andFieldthe name of the field: changing the display labels of events, arms or fields doesn't solve their queries. Their labels (EventLabelandDescription) and the other columns (e.g.LinkorDAG) are taken from the new report, so a query whose label or link changed is still one pending query. -
Reports created before
EventLabelexisted:rd_query()could store event labels inEventwhen factor labels were available. Reports fromrd_event()already stored unique event names there, but used labels in their defaultQuerytext. Recognised legacy labels and default missing-event query texts are normalised to unique event names. Shared labels cannot be resolved automatically. -
Miscorrected detection: A
Miscorrectedlabel is assigned to a query that would otherwise beNewwhen the old report has a query of the same record (Identifier), event (Event) and repetition (Repetition), when both reports have these columns, and of the same variable: the sameFieldwhen both reports have it, or else the sameDescription. This signals a likely re-issued or modified query. New queries without such a query in the old report areNew, also when there are several of them for the same field.
See Also
Other query functions:
rd_event(),
rd_export(),
rd_query()
Examples
# Minimal reproducible example
old <- data.frame(
Identifier = c("100-1", "100-2", "200-1"),
Description = c("age check", "weight check", "lab miss"),
Query = c("is.na(age)", "is.na(weight)", "missing lab result"),
Code = c("100-1-1", "100-2-1", "200-1-1"),
stringsAsFactors = FALSE
)
new <- data.frame(
Identifier = c("100-1", "200-1", "300-1"),
Description = c("age check", "lab miss", "new query"),
Query = c("is.na(age)", "missing lab result (clarify)", "is.na(x)"),
stringsAsFactors = FALSE
)
res <- check_queries(old = old, new = new, report_title = "My Query Comparison")
# detailed table
head(res$queries)
# HTML summary (if in an RMarkdown or interactive viewer)
res$results
Change Checkboxes Names to Option Names
Description
This function updates the names of checkboxes in the dataset and dictionary to reflect the names of their options.
Usage
checkbox_names(data, dic, labels, checkbox_labels = c("No", "Yes"))
Arguments
data |
Dataset containing the REDCap data. |
dic |
Dataset containing the REDCap dictionary. |
labels |
Named character vector with the names of the variables in the data and their corresponding REDCap labels. |
checkbox_labels |
Character vector specifying the names for the two options of each checkbox variable. The default is |
Subset of COVICAN's Database
Description
A random sample of the COVICAN study. An international, multicentre cohort study of cancer patients with COVID-19 to describe the epidemiology, risk factors, and clinical outcomes of co-infections and superinfections in onco-haematological patients with COVID-19.
Usage
data(covican)
Format
A data frame with 342 rows and 56 columns
- record_id:
Identifier of each record. This information does not match the real data.
- redcap_event_name:
Auto-generated name of the events
- redcap_data_access_group:
Auto-generated name of each center. This information does not match the real data.
- inc_1:
Inclusion criteria of 'Patients older than 18 years' (0 = No ; 1 = Yes)
- inc_2:
Inclusion criteria of 'Cancer patients' (0 = No ; 1 = Yes)
- inc_3:
Inclusion criteria of 'Diagnosed of COVID-19' (0 = No ; 1 = Yes)
- exc_1:
Exclusion criteria of 'Solid tumour remission >1 year' (0 = No ; 1 = Yes)
- screening_fail_crit:
Indicator of non-compliance with inclusion and exclusion criteria (0 = compliance ; 1 = non-compliance)
- d_birth:
Date of birth (y-m-d). This date does not correspond to the original.
- d_admission:
Date of first visit (y-m-d). This date does not correspond to the original.
- age:
Age in years
- dm:
Indicator of diabetes (0 = No ; 1 = Yes)
- type_dm:
Type of diabetes (1 = No complications ; 2 = End-organ diabetes-related disease)
- copd:
Indicator of chronic obstructive pulmonary disease (0 = No ; 1 = Yes)
- fio2:
Fraction of inspired oxygen in percentage
- available_analytics:
Indicator of blood test available (0 = No ; 1 = Yes)
- potassium:
Potassium in mmol/L
- resp_rate:
Respiratory rate in bpm
- leuk_lymph:
Indicator of leukemia or lymphoma (0 = No ; 1 = Yes)
- acute_leuk:
Indicator of acute leukemia (0 = No ; 1 = Yes)
- type_underlying_disease...:
Checkbox with the type of underlying disease (0 = Haematological cancer ; 1 = Solid tumour)
- underlying_disease_hemato...:
Checkbox with the type of underlying disease (1 = Acute myeloid leukemia ; 2 = Myelodysplastic syndrome ; 3 = Chronic myeloid leukaemia ; 4 = Acute lymphoblastic leukaemia ; 5 = Hodgkin lymphoma ; 6 = Non Hodgkin lymphoma ; 7 = Multiple myeloma ; 8 = Myelofibrosis ; 9 = Aplastic anaemia ; 10 = Chronic lymphocytic leukaemia ; 11 = Amyloidosis ; 12 = Other)
- urine_culture:
Indicator of urine culture: (0 = Not done ; 1 = Done)
- ....factor:
Labels of the different variables
Note
List with three data frames: the first one with the data, the second one with the dictionary (codebook) of the REDCap project and the last one with the instrument-event mappings of the REDCap project.
References
Gudiol, C., Durà-Miralles, X., Aguilar-Company, J., Hernández-Jiménez, P., Martínez-Cutillas, M., Fernandez-Avilés, F., Machado, M., Vázquez, L., Martín-Dávila, P., de Castro, N., Abdala, E., Sorli, L., Andermann, T. M., Márquez-Gómez, I., Morales, H., Gabilán, F., Ayaz, C. M., Kayaaslan, B., Aguilar-Guisado, M., Herrera, F. Royo-Cebrecos C, Peghin M, González-Rico C, Goikoetxea J, Salgueira S, Silva-Pinto A, Gutiérrez-Gutiérrez B, Cuellar S, Haidar G, Maluquer C, Marin M, Pallarès N, Carratalà J. (2021). Co-infections and superinfections complicating COVID-19 in cancer patients: A multicentre, international study. The Journal of infection, 83(3), 306–313. https://doi.org/10.1016/j.jinf.2021.07.014
Print a query report
Description
Shows a short summary of the output of rd_query(), rd_event() or check_queries(): the number of queries per
variable and event (per state in check_queries()). The output is still a list: the queries are in $queries
and the formatted summary in $results.
Usage
## S3 method for class 'REDCapDM_report'
print(x, ...)
Arguments
x |
Output of |
... |
Not used. |
Value
x, invisibly.
Examples
report <- rd_query(covican, variables = c("copd", "age"), expression = c("is.na(x)", "x > 70"),
event = "baseline_visit_arm_1")
report
head(report$queries)
Transform Checkbox Variables in a REDCap Project
Description
This function is used to process checkbox variables in a REDCap dataset. By default, it changes their default categories ("Unchecked" and "Checked") to new ones ("No" and "Yes). Optionally, the function can also evaluate the branching logic for checkbox fields and adjust the data and dictionary accordingly.
Usage
rd_checkbox(
project = NULL,
data = NULL,
dic = NULL,
event_form = NULL,
checkbox_labels = c("No", "Yes"),
checkbox_names = TRUE,
na_logic = "missing"
)
Arguments
project |
A list containing the REDCap data, dictionary, and event mapping (expected |
data |
A |
dic |
A |
event_form |
Only applicable for longitudinal projects (presence of events). Event-to-form mapping for longitudinal projects. |
checkbox_labels |
Character vector of length 2 for labels of unchecked/checked values. Default: |
checkbox_names |
Logical. If |
na_logic |
Controls how missing values are set based on branching logic. Must be one of |
Details
Checkbox columns are expected in REDCap wide format (
field___code).Branching logic evaluation requires
event_formfor longitudinal projects.Names are cleaned and truncated to 60 characters; uniqueness is enforced.
Fields that cannot be evaluated are listed in
results.In the branching logic and calculations, the options get their new names and keep their codes
0and1, as in REDCap logic (e.g.[cb(1)] = '1'is[cb_option] = '1', and[cb(1)] + [cb(2)] >= 2is[cb_option] + [cb_other] >= 2).rd_dictionary()writes the labels when it translates the logic into R.
Value
A list with:
- data
Transformed dataset with the checkbox options optionally renamed. When the data has the
.factorversions of the options, the original columns keep their codes 0/1 and the.factorversions take the labels ofcheckbox_labels; otherwise the original columns are replaced by factors with these labels.- dictionary
Updated dictionary with checkbox fields expanded and optionally renamed.
- event_form
The
event_formpassed in (if applicable).- results
Summary of transformations and any fields needing review.
See Also
Other process functions:
rd_dates(),
rd_delete_vars(),
rd_dictionary(),
rd_factor(),
rd_insert_na(),
rd_recalculate(),
rd_rlogic(),
rd_split(),
rd_transform()
Examples
# Basic usage with a project object
res <- rd_checkbox(covican)
# With custom labels
res <- rd_checkbox(data = covican$data,
dic = covican$dictionary,
event_form = covican$event_form,
checkbox_labels = c("Not present", "Present"))
# Keep original checkbox names
res <- rd_checkbox(covican, checkbox_names = FALSE)
# Longitudinal project with NA logic
res <- rd_checkbox(data = covican$data,
dic = covican$dictionary,
event_form = covican$event_form,
na_logic = "eval")
Transform Dates and Datetimes in REDCap Data
Description
Converts date and datetime fields in a REDCap dataset to appropriate R classes.
Usage
rd_dates(project = NULL, data = NULL, dic = NULL, event_form = NULL)
Arguments
project |
A list containing the REDCap data, dictionary, and event mapping (expected |
data |
A |
dic |
A |
event_form |
Only applicable for longitudinal projects (presence of events). Event-to-form mapping for longitudinal projects. |
Details
The function performs the following tasks:
Detects date and datetime fields from the REDCap dictionary (
date_*anddatetime_*validation types).Converts date fields to
Dateclass.Converts datetime fields to
POSIXctclass, treating empty strings asNA. The texts are read in UTC, whatever the time zone of the session (e.g.TZ = "Europe/Paris"): the time is kept as it is written in REDCap (e.g.2024-01-05 10:30is 10:30 UTC). The fields that are alreadyPOSIXctare left as they are.Each value is converted on its own (
YYYY-MM-DDorYYYY/MM/DD, with or without time): a value that isn't a date or a datetime (e.g. a Missing Data Code that wasn't removed) is set toNA, and a warning lists the fields and the values.
Value
A list with the following elements:
- data
The transformed dataset with date and datetime fields formatted as
DateandPOSIXct.- dictionary
The original REDCap dictionary passed to the function.
- event_form
The original event-form mapping (if applicable).
- results
A summary of the transformations performed.
See Also
Other process functions:
rd_checkbox(),
rd_delete_vars(),
rd_dictionary(),
rd_factor(),
rd_insert_na(),
rd_recalculate(),
rd_rlogic(),
rd_split(),
rd_transform()
Examples
result <- rd_dates(covican)
transformed_data <- result$data
Delete Variables from REDCap Dataset and Dictionary
Description
Deletes selected variables from a REDCap dataset and its dictionary, keeping them consistent and preserving variable labels.
Usage
rd_delete_vars(
project = NULL,
data = NULL,
dic = NULL,
event_form = NULL,
vars = NULL,
pattern = NULL,
forms = NULL
)
Arguments
project |
A list containing the REDCap data, dictionary, and event mapping (expected |
data |
A |
dic |
A |
event_form |
Only applicable for longitudinal projects (presence of events). Event-to-form mapping for longitudinal projects. |
vars |
Optional. A character vector of variable names to remove from both the dataset and dictionary. |
pattern |
Optional. A character vector of regular expression patterns. Variables matching these patterns will be removed from the dataset and dictionary. |
forms |
Optional. A character vector of form names (as in the |
Details
Ensure that at least one of
vars,patternorformsis specified.Removes specified variables and their factor versions (e.g.,
variable.factor) from the dataset.Removes matching variables from the dictionary.
Warns about factor versions of variables matching patterns, recommending use of
rd_factor()if necessary.With
forms, every variable of the form is removed: its factor versions, checkbox options, recalculated versions (_recalc) and the form's_completeand_timestampfields. The record identifier is always kept. The forms are also removed fromevent_form, and so are the rows of the repeating instruments among them.
Value
A list containing:
- data
The updated dataset with specified variables removed.
- dictionary
The updated REDCap dictionary.
- event_form
The event-form mapping (if applicable), without the removed forms.
- results
A summary message describing the variable removal operation.
See Also
Other process functions:
rd_checkbox(),
rd_dates(),
rd_dictionary(),
rd_factor(),
rd_insert_na(),
rd_recalculate(),
rd_rlogic(),
rd_split(),
rd_transform()
Examples
# Delete specific variables by name
result <- rd_delete_vars(
project = covican,
vars = c("potassium", "leuk_lymph")
)
# Delete variables matching patterns (here, the inclusion and exclusion criteria)
result <- rd_delete_vars(
data = covican$data,
dic = covican$dictionary,
pattern = c("^inc_", "^exc_")
)
# Delete every variable of a form
result <- rd_delete_vars(
project = covican,
forms = "laboratory_findings"
)
Transform the data dictionary and handle branching logic
Description
Updates a REDCap data dictionary by converting branching logic and calculation expressions into valid R expressions. This ensures that conditional display rules and calculated fields in the dictionary can be programmatically evaluated with the dataset. Any variables that cannot be converted are reported in the results.
Usage
rd_dictionary(project = NULL, data = NULL, dic = NULL, event_form = NULL)
Arguments
project |
A list containing the REDCap data, dictionary, and event mapping (expected |
data |
A |
dic |
A |
event_form |
Only applicable for longitudinal projects (presence of events). Event-to-form mapping for longitudinal projects. |
Details
The function performs the following tasks:
Evaluates and transforms branching logic expressions into valid R expressions using
rd_rlogic.Evaluates and converts calculation expressions for fields of type
calc.Keeps in REDCap syntax, with the codes of the options, the logic that uses as a number a variable already converted into a factor (e.g.
[score] >= 3or[a] + [b]afterrd_factor()): it can't be written as R logic of the factors.rd_rlogic()andrd_query()evaluate it with the codes, as REDCap does. The same happens with the logic that uses variables of other events.Generates a results summary table listing any variables that could not be converted.
Value
A list with the following elements:
- data
The original dataset passed to the function.
- dictionary
The updated data dictionary with modified branching logic and calculations.
- event_form
The original event-form mapping (if applicable).
- results
A summary of the transformations, including any variables with unconverted branching logic.
See Also
Other process functions:
rd_checkbox(),
rd_dates(),
rd_delete_vars(),
rd_factor(),
rd_insert_na(),
rd_recalculate(),
rd_rlogic(),
rd_split(),
rd_transform()
Examples
## Not run:
result <- rd_dictionary(covican)
print(result$results)
updated_dic <- result$dictionary
## End(Not run)
Identify Missing Events in REDCap Data
Description
Helps identify records in a REDCap longitudinal project that are missing one or more specified events. Because REDCap typically omits empty events from exports, an event that contains no data for a record will not appear. This function finds those absent events (not whether the events are complete) and returns a per-record query table and a summarized HTML report.
Usage
rd_event(
project = NULL,
data = NULL,
dic = NULL,
event_form = NULL,
event,
filter = NA,
query_name = NA,
add_to = NA,
report_title = NA,
report_zeros = FALSE,
link = list(),
addTo = deprecated()
)
Arguments
project |
A list containing the REDCap data, dictionary, and event mapping (expected |
data |
A |
dic |
A |
event_form |
Only applicable for longitudinal projects (presence of events). Event-to-form mapping for longitudinal projects. |
event |
Character vector with one or more REDCap event names to check for missing records. |
filter |
Optional. A single character string containing a filter expression that selects the records to check. Example: |
query_name |
Optional character vector describing each query: one message for all the events, or one message for each event of |
add_to |
Optional output of a previous |
report_title |
Optional string specifying the title of the final report. Defaults to |
report_zeros |
Logical, include events with zero queries in the report. Default is |
link |
Optional list containing project information ( |
addTo |
Value
A list of class REDCapDM_report, which prints a short summary (see print.REDCapDM_report()), with two elements:
queriesA data frame listing records missing the specified events. Columns:
Identifier(the record identifier,record_idor else the first field of the dictionary, whichfiltercan use by its name),DAG,Event(the unique event name),EventLabel(its label),Instrument,Field,Repetition,Description,Query,Code, and optionallyLink. If no queries are found this will be an empty data frame with the expected columns.resultsAn HTML table (knitr::kable styled with kableExtra) summarising the number of missing records per event. Returned as
knitr::kable(HTML).
See Also
Other query functions:
check_queries(),
rd_export(),
rd_query()
Examples
# Minimal reproducible example
data0 <- data.frame(
record_id = c("100-1", "100-2", "200-1"),
redcap_event_name = c("baseline_arm_1", "baseline_arm_1", "follow_up_arm_1"),
redcap_event_name.factor = factor(c("Baseline", "Baseline", "Follow-up")),
stringsAsFactors = FALSE
)
# Suppose we want to check that every record has the follow-up event
res <- rd_event(
data = data0,
dic = data.frame(), # placeholder dictionary
event = "follow_up_arm_1",
report_zeros = TRUE
)
# Records missing the event:
res$queries
# HTML summary (in RMarkdown or Viewer)
res$results
Export Queries to an Excel File
Description
Export a query dataset (e.g., from rd_query or rd_event) to an .xlsx file. The function can optionally convert a column of URLs into Excel hyperlinks and apply password protection to the worksheet.
Usage
rd_export(
project = NULL,
queries = NULL,
column = NULL,
sheet_name = NULL,
path = NULL,
password = NULL
)
Arguments
project |
A list containing the dataframe of queries and results (expected |
queries |
A data frame of identified queries. |
column |
Name of the column containing URLs to convert into hyperlinks. If |
sheet_name |
Name of the Excel sheet in the resulting |
path |
File path for saving the |
password |
Optional password to protect the worksheet from edits. |
Value
An .xlsx file written to the specified path.
See Also
Other query functions:
check_queries(),
rd_event(),
rd_query()
Examples
if (requireNamespace("openxlsx", quietly = TRUE)) {
result <- rd_query(covican, variables = "age", expression = "x > 80")
rd_export(
result,
sheet_name = "My Queries",
path = file.path(tempdir(), "queries.xlsx")
)
}
Convert Variables to Factors in a REDCap Dataset
Description
Converts variables in a REDCap dataset with associated .factor columns into actual factor variables, while allowing the exclusion of specific variables. Ensures consistency with the dataset and preserves variable labels.
Usage
rd_factor(
project = NULL,
data = NULL,
dic = NULL,
event_form = NULL,
exclude = NULL
)
Arguments
project |
A list containing the REDCap data, dictionary, and event mapping (expected |
data |
A |
dic |
A |
event_form |
Only applicable for longitudinal projects (presence of events). Event-to-form mapping for longitudinal projects. |
exclude |
Optional character vector of variable names (use original names without the |
Details
The function looks for columns ending in .factor and replaces the original variable values with those .factor values (converted to factors). The variables in exclude, the system columns below and the variables whose labels are of several codes (with a warning) keep both columns. A .factor column that isn't a factor (e.g. text, after modifying the data) is converted to a factor, with the levels in the order of the options of the dictionary. It preserves variable labels. The exclude argument must contain base variable names (no .factor suffix); if any .factor names are passed to exclude the function will throw an informative error. The columns redcap_event_name, redcap_repeat_instrument and redcap_data_access_group (and their .factor counterparts) are handled specially to avoid altering event or access-group data. A .factor column whose original variable no longer exists (e.g. removed with rd_delete_vars()), also of these columns, is removed with a warning.
Use rd_factor() before rd_dictionary(): the branching logic and calculations that rd_dictionary() translates to R compare the variables with their original codes, so they stop working once the variables are factors. If the dictionary already has logic translated to R that uses any of the converted variables, a warning is shown.
Value
A list with the following elements:
- data
The transformed dataset with
.factorcolumns applied as factors.- dictionary
The dictionary used (unchanged).
- event_form
The event-form mapping used (if applicable).
- results
A brief text summary of the transformation.
See Also
Other process functions:
rd_checkbox(),
rd_dates(),
rd_delete_vars(),
rd_dictionary(),
rd_insert_na(),
rd_recalculate(),
rd_rlogic(),
rd_split(),
rd_transform()
Examples
## Not run:
result <- rd_factor(covican)
result <- rd_factor(covican, exclude = c("available_analytics", "urine_culture"))
transformed_data <- result$data
## End(Not run)
Insert Missing Values Using a Filter
Description
Sets selected variables to NA when a filter condition is satisfied. Useful for managing checkboxes or other fields without explicit gatekeeper questions.
Usage
rd_insert_na(
project = NULL,
data = NULL,
dic = NULL,
event_form = NULL,
vars,
filter
)
Arguments
project |
A list containing the REDCap data, dictionary, and event mapping (expected |
data |
A |
dic |
A |
event_form |
Only applicable for longitudinal projects (presence of events). Event-to-form mapping for longitudinal projects. |
vars |
Character vector of variable names to set to |
filter |
A single logical expression (as string). Rows where the filter evaluates to |
Details
Each variable is only updated in rows/events where both the variable and filter are present.
If the variable has a
.factorversion, it is updated too.For longitudinal projects,
event_formmust be provided for proper event-level filtering.Only one filter expression is allowed.
The columns of the filter must be known to check their events: use their names (e.g.
age > 30),data$age,data[["age"]],.data[[field]],data[, "age"]ordata[, 3]. A filter that uses the data in another way (e.g.dplyr::pull(data, "age")orrev(data)[, 2]), finds objects by their name or evaluates code (e.g.get("age")oreval(parse(text = "age"))), or whose result depends on other columns of the data (e.g. through a function of your session that reads them) stops with an error.Variables and filter columns must exist in both
dataanddictionary: their.factorand_mdcversions and the options of a checkbox (e.g.cb___1) are checked with their field. The objects of your session used in the filter don't need to be in them.
Value
A list with:
- data
The dataset with
NAinserted where the filter applies.- dictionary
The unchanged dictionary.
- event_form
The
event_formpassed in (if applicable).- results
Summary message of the changes applied.
See Also
Other process functions:
rd_checkbox(),
rd_dates(),
rd_delete_vars(),
rd_dictionary(),
rd_factor(),
rd_recalculate(),
rd_rlogic(),
rd_split(),
rd_transform()
Examples
# Set 'potassium' to NA where age < 65
result <- rd_insert_na(
covican,
vars = "potassium",
filter = "age < 65"
)
table(is.na(result$data$potassium))
Plot Missing Data Overview (Barplot, Longitudinal Heatmap or Record Map)
Description
Generates a visual summary of missing data for variables in a REDCap dataset or list structure. With by = "vars" (default), cross-sectional (single-event) studies get a barplot showing the proportion or count of missing values per variable, and longitudinal studies (with the column redcap_event_name, also with a single event) get a heatmap illustrating missingness across events and variables. With by = "record", the plot shows one row per record and one column per variable, with the missing values painted.
Usage
rd_missplot(
data,
sort_by_missingness = TRUE,
max_vars = NULL,
show_percentages = TRUE,
use_field_labels = TRUE,
drop_complete = TRUE,
max_label_length = 40,
by = c("vars", "record"),
events = NULL,
forms = NULL
)
Arguments
data |
A |
sort_by_missingness |
Logical. Variables are ordered from highest to lowest number of missing values (the count, also when |
max_vars |
Integer. If specified, only |
show_percentages |
Logical. Displays missingness as percentages. Only used with |
use_field_labels |
Logical. Uses field labels from the dictionary for axis labels instead of variable names. Default |
drop_complete |
Logical. Variables with 0 missing values are excluded from the plot. Default |
max_label_length |
Integer. Maximum number of characters of the axis labels: longer labels are shortened. When several variables share a label, their variable name is then added to it in parentheses, so these labels can be longer. Use |
by |
Character. |
events |
Character vector. Only for longitudinal projects: events to plot, by their unique name (e.g. |
forms |
Character vector. Only plot the variables of these forms (instrument names as in the |
Details
With by = "vars", the function automatically detects whether the input dataset contains longitudinal event information. If redcap_event_name is detected in the data columns, a missingness heatmap grouped by event is produced (with by = "record", see below).
When the event-form mapping is available (event_form element of the list), each variable is only evaluated in the events where its form is collected; the other cells of the heatmap are left blank.
With by = "record", longitudinal projects get one panel per event, each with the variables collected in that event. By default only the first event is plotted (with a warning); use events to choose others. Records without data in an event are shown in grey in that event's panel. With repeated instruments and repeating events, each repetition is a row of its own, and the cells of variables that are not collected in that row are shown in light grey. Every row is labelled with its record identifier.
Value
A ggplot2 object representing a missingness barplot, a longitudinal missingness heatmap or a record-level missingness map.
Examples
## Not run:
# Missing values per variable and event
rd_missplot(covican)
# Missing values record by record in the baseline laboratory findings
rd_missplot(covican, by = "record", events = "baseline_visit_arm_1",
forms = "laboratory_findings")
## End(Not run)
Identification of Queries
Description
Detects and summarizes queries in a REDCap dataset based on specified expressions, filters, or a defined branching logic. Useful for identifying missing values, out-of-range values, or values that do not meet predefined criteria.
Usage
rd_query(
project = NULL,
variables = NA,
expression = NA,
negate = FALSE,
event = NA,
filter = NA,
add_to = NA,
variables_names = NA,
query_name = NA,
instrument = NA,
report_title = NA,
report_zeros = FALSE,
by_dag = FALSE,
link = list(),
data = NULL,
dic = NULL,
event_form = NULL,
addTo = deprecated()
)
Arguments
project |
A list containing the REDCap data, dictionary, and event mapping (expected |
variables |
Character vector of variable names to check for queries. |
expression |
Character vector of R conditions, written as text, to evaluate for each variable, where |
negate |
Logical, if |
event |
REDCap event(s) to analyze in longitudinal projects. If it isn't given, the events where the form of each variable is collected are taken from |
filter |
Optional filter of the rows to check, written as text (e.g. |
add_to |
Optional output of a previous |
variables_names |
Optional character vector of descriptions for each variable. Defaults to the variables labels in the dictionary. |
query_name |
Optional character vector describing each query. Defaults to a standard format: |
instrument |
Optional REDCap instrument(s) for each variable. Defaults to the instrument reported in the dictionary. |
report_title |
Optional string specifying the title of the final report. Defaults to |
report_zeros |
Logical, include variables with zero queries in the report. Default is |
by_dag |
Logical, split results by Data Access Group (DAG). Default is |
link |
Optional list containing project information ( |
data |
A |
dic |
A |
event_form |
Only applicable for longitudinal projects (presence of events). Event-to-form mapping for longitudinal projects. |
addTo |
Details
The function performs the following steps:
Applies user-specified expressions to the selected variables to detect queries.
Optionally negates the expressions to find values that do not satisfy the condition.
Handles REDCap branching logic, converting it into R-compatible expressions for evaluation.
Applies additional user-specified filters before identifying queries.
Generates structured query results with metadata including:
Identifier: the record identifier,
record_idor else the first field of the dictionary (e.g.subject_id), whatever its position in the data. Filters and expressions can use it by its name.DAG (if present)
Event (the unique event name, e.g.
baseline_arm_1), EventLabel (its label, e.g.Baseline (Arm 1: Drug A)) and InstrumentField, Repetition, Description, Query statement
Optional link to REDCap entry
Optionally combines results with previous query outputs using
add_to. The event of a query is its unique event name: a label can be renamed in REDCap or be the same in several arms. The previous queries take the current label of their events.Produces a summarized report, optionally including variables with zero queries.
If branching logic cannot be translated by
rd_rlogic(), the function warns and checks the variable without applying that branching logic. Review these queries manually or provide an appropriatefilter.
Value
A list of class REDCapDM_report, which prints a short summary (see print.REDCapDM_report()), containing:
- queries
A data frame or a list of data frames (if
by_dag = TRUE, one per DAG) with detailed query information for each record.- results
A formatted report (HTML table) summarizing total queries per variable and event; with
by_dag = TRUE, a list with one table per DAG.
See Also
Other query functions:
check_queries(),
rd_event(),
rd_export()
Examples
## Not run:
# Identify missing values for multiple variables
result <- rd_query(covican,
variables = c("copd", "age"),
expression = c("is.na(x)", "x %in% NA"),
event = "baseline_visit_arm_1"
)
result$results
# Identify values exceeding a threshold
result <- rd_query(covican,
variables = "age",
expression = "x > 20",
event = "baseline_visit_arm_1"
)
# Apply a filter to select subset of data
result <- rd_query(covican,
variables = "potassium",
expression = "is.na(x)",
event = "baseline_visit_arm_1",
filter = "available_analytics == '1'"
)
## End(Not run)
Recalculate and Verify Calculated Fields in REDCap Data
Description
Recalculates fields marked as calculated in the REDCap dictionary, compares them with the original values, and reports discrepancies. If any differences are found, new recalculated fields are added to the dataset and dictionary with _recalc appended to the names.
Usage
rd_recalculate(
project = NULL,
data = NULL,
dic = NULL,
event_form = NULL,
exclude = NULL
)
Arguments
project |
A list containing the REDCap data, dictionary, and event mapping (expected |
data |
A |
dic |
A |
event_form |
Only applicable for longitudinal projects (presence of events). Event-to-form mapping for longitudinal projects. |
exclude |
Optional. Character vector of field names to exclude from recalculation. |
Details
Fields of type
calcin the dictionary are recalculated. As in REDCap, a calculation without a numeric result (e.g. a division by zero) is blank (NA).Recalculated values are compared with the original values, both rounded to three decimals (e.g. 1.0004 and 1 are equal).
If differences exist, new fields
[field_name]_recalcare added to the dataset and dictionary, with the label of the original field followed by(Recalculated). Running the function again on its output updates these fields instead of duplicating them.The fields added by this function are recognised because they are calculated fields with the same calculation as the original field and, when the dictionary has the column
field_label, its label followed by(Recalculated)(or by(Recalculate), the label of previous versions of the package, which are also recognised). No other field or column is overwritten: if[field_name]_recalcis already one of them, the recalculated values are saved in[field_name]_recalc_1(or_2, ...) with a warning.Works for single-event projects; for longitudinal projects,
event_formmust be provided.The calculation of each field is translated to R with
rd_rlogic(): calculations that can't be translated (e.g. with smart variables or functions that it doesn't know) are not recalculated, andTranscribed?isNo.The original and recalculated values are compared as numbers when both are numbers, also written as text (e.g.
'100000', the result ofif()with texts) or asTRUE/FALSE(the 1/0 of a condition), rounded to 3 decimals: the comparison doesn't depend on how R writes the numbers.A calculated field of the dictionary that isn't in the data can't be compared: a warning is shown, and its
Is equal?andDifferent valuesareNA.Existing generated columns are refreshed even when the original values now agree with the calculation. If a formula cannot be translated or evaluated, its previously generated column is set to
NAwith a warning. Excluded fields and their generated columns are left unchanged.Unsupported formulas are reported as non-transcribed in
results; they do not stop the recalculation of other fields. Restrictions on repeated-source references are those ofrd_rlogic().
Value
A list with:
- data
The dataset with new
_recalcfields for any differing calculated fields.- dictionary
Updated dictionary including the new
_recalcfields.- event_form
The
event_formpassed in (if applicable).- results
Summary report of the recalculation process, including tables of discrepancies.
See Also
Other process functions:
rd_checkbox(),
rd_dates(),
rd_delete_vars(),
rd_dictionary(),
rd_factor(),
rd_insert_na(),
rd_rlogic(),
rd_split(),
rd_transform()
Examples
# Recalculate all calculated fields
## Not run:
results <- rd_recalculate(
data = covican$data,
dic = covican$dictionary,
event_form = covican$event_form
)
## End(Not run)
# Recalculate but exclude some variables
## Not run:
results <- rd_recalculate(
project = covican,
exclude = c("age", "screening_fail_crit")
)
## End(Not run)
Translate REDCap Logic to R Logic
Description
Converts a REDCap logic expression into R-compatible logic. Processes one logic expression (logic) for one target variable (var) at a time. Supports common REDCap operators (and, or, =, <, >, etc.) and handles event-specific logic in longitudinal projects and repeated instruments. Logic involving smart variables may require manual review.
Usage
rd_rlogic(
project = NULL,
data = NULL,
dic = NULL,
event_form = NULL,
logic,
var
)
Arguments
project |
A list containing the REDCap data, dictionary, and event mapping (expected |
data |
A |
dic |
A |
event_form |
Only applicable for longitudinal projects (presence of events). Event-to-form mapping for longitudinal projects. |
logic |
A single REDCap logic string (e.g., |
var |
A single string specifying the target variable the logic applies to. When |
Details
Translates REDCap operators and functions into R equivalents:
-
=→==,<>→!=,and→&,or→|. Converts the functions
if(),datediff(),round(),rounddown(),roundup(),sum(),mean(),median(),min(),max(),mod(),exponential(),isnumber(),isblankormissingcode(),contains(),not_contain(),starts_with(),ends_with(),left(),right(),mid(),find(),replace_text(),concat(),concat_ws(),upper(),lower(),trim(),length(),stdev(),isinteger(),year(),month()andday()to R equivalents.As in REDCap,
sum(),mean(),median(),min()andmax()are computed for each row and ignore blank values.
-
Handles date transformations and empty strings (
'') →NA.Adjusts logic for longitudinal data using
event_formif provided.Evaluates the translated R logic against the dataset and returns the results.
With repeated instruments and repeating events, the logic is evaluated in the rows where
varis collected. As in REDCap, in a repeating instrument the variables of the other forms take the value of the base row of the same record and event. A variable of another repeating instrument or repeating event can be used with its instance ([event][field][current-instance], the instance of the same number). Without it, the logic can't be translated when the instance to use isn't known:[field]of another instrument that repeats in the events ofvar, or[event][field]when its form repeats in that event or the event repeats.[event][field]of a form collected once in that event is valid, although the form repeats in other events.As in REDCap,
datediff()returns the absolute difference unless its last argument istrue, its units are"y"(years of 365.2425 days),"M"(months of 30.44 days),"d","h","m"(minutes) and"s","today"is the current date and"now"the current date and time. With two time fields (e.g.HH:MM), it is the difference between the two times of the same day, and its date format (e.g.'hhmm') is not used.The same variable can be used in several events (e.g.
[visit_2_arm_1][weight] - [visit_1_arm_1][weight]).Logic with smart variables or other REDCap functions may require manual inspection.
Value
A list with:
- rlogic
The translated R expression. It can reference auxiliary columns or internal helpers used during translation; it is not necessarily reusable against the original dataset. Use
evaloreval_datafor the evaluated result.- eval
The evaluated values in input row order, with
NAoutside the target events and instrument rows. A constant expression can return a single value for a non-longitudinal dataset without repeating instruments; useeval_datafor one value per input row.- eval_data
A
data.framewith the record identifier, the event and repetition columns present in the dataset (redcap_event_name,redcap_repeat_instrument,redcap_repeat_instance) andeval, to identify the record of each evaluated value.
See Also
Other process functions:
rd_checkbox(),
rd_dates(),
rd_delete_vars(),
rd_dictionary(),
rd_factor(),
rd_insert_na(),
rd_recalculate(),
rd_split(),
rd_transform()
Examples
# Translate a single REDCap logic expression for one variable
covican |>
rd_rlogic(
logic = "if([exc_1]='1' or [inc_1]='0' or [inc_2]='0' or [inc_3]='0', 1, 0)",
var = "screening_fail_crit"
)
Split a REDCap dataset by form or event
Description
Splits a REDCap dataset into separate datasets by form or event using the data dictionary. Supports both longitudinal and non-longitudinal projects and can return wide or long formats for repeated measures.
Usage
rd_split(
project = NULL,
data = NULL,
dic = NULL,
event_form = NULL,
which = NULL,
by = "form",
wide = FALSE
)
Arguments
project |
A list containing the REDCap data, dictionary, and event mapping (expected |
data |
A |
dic |
A |
event_form |
Only applicable for longitudinal projects (presence of events). Event-to-form mapping for longitudinal projects. |
which |
Optional. A single form or event to extract. If not provided, all forms or events are returned. |
by |
Character. Criteria to split the dataset: |
wide |
Logical. If |
Details
Handles checkbox variables and REDCap default variables (
_complete,_timestamp) appropriately.Columns of the data that aren't fields of the dictionary, nor the
.factoror_mdcversions of its fields or the options of its checkbox fields (or the.factorversion of the_completefield of a form), stop the function with an error that names them.For form-based splits in longitudinal projects, uses
event_formto map variables to events.Wide format expands repeated instances into multiple columns per record. A form with only the record identifier gives one row per record.
Filtering by
whichallows extracting a single form or event.Projects with repeated instruments are handled by filtering on the
redcap_repeat_instrumentvariable (its codes). The column shows the label of each instrument (its factor version, fromredcap_data()), or its code when the label is missing.
Value
Depending on which and wide:
- data
Without
which, a tibble with one row per form (columnsform,eventsin longitudinal projects, anddf) or per event (columnseventsanddf): the dataset of each form or event is in the list-columndf(e.g.result$data$df[[1]], orresult$data$df[result$data$form == "demographics"][[1]]). Withwide = TRUE, the tibble of the forms also has the columnmax_repeated_instance, the largest number of rows of a record in each form (its events and repetitions): the wide columns are numbered by the position of each row of the record, not by its instance (e.g. the instances 2 and 5 of a record are the columns_1and_2, and the maximum is 2). Withwhich, thedata.frameof that form or event.- dictionary
The original REDCap dictionary.
- event_form
The original event-form mapping (if applicable).
- results
A summary message of the splitting operation.
See Also
Other process functions:
rd_checkbox(),
rd_dates(),
rd_delete_vars(),
rd_dictionary(),
rd_factor(),
rd_insert_na(),
rd_recalculate(),
rd_rlogic(),
rd_transform()
Examples
# Split by form and return wide format
result <- covican |>
rd_split(by = "form", wide = TRUE)
print(result)
# Split by event (long format)
result <- covican |>
rd_split(by = "event")
print(result)
Transformation of the Raw Data
Description
Transforms the raw REDCap data read by the redcap_data function. The function runs in one-step pipeline the functions dedicated to processing the data (rd_delete_vars(), rd_dates(), rd_recalculate(), rd_checkbox(), rd_factor(), rd_dictionary() and, with final_format, rd_split()) and returns the transformed data and dictionary, along with a summary of each step done. rd_insert_na() is not part of it: its filters are specific to each project, so apply it separately.
Usage
rd_transform(
project = NULL,
data = NULL,
dic = NULL,
event_form = NULL,
checkbox_labels = c("No", "Yes"),
na_logic = "none",
exclude_recalc = NULL,
exclude_factor = NULL,
delete_vars = NULL,
delete_pattern = NULL,
final_format = "raw",
which_event = NULL,
which_form = NULL,
wide = NULL
)
Arguments
project |
A list containing the REDCap data, dictionary, and event mapping (expected |
data |
A |
dic |
A |
event_form |
Only applicable for longitudinal projects (presence of events). Event-to-form mapping for longitudinal projects. |
checkbox_labels |
Character vector of length 2 for labels of unchecked/checked values. Default: |
na_logic |
Controls how missing values are set based on the branching logic of a checkbox. Must be one of |
exclude_recalc |
Optional. Character vector of field names to exclude from recalculation. |
exclude_factor |
Optional character vector of variable names (use original names without the |
delete_vars |
Optional. A character vector of variable names to remove from both the dataset and dictionary. |
delete_pattern |
Optional. A character vector of regular expression patterns. Variables matching these patterns will be removed from the dataset and dictionary. |
final_format |
Character string indicating the final format of the data. Options are |
which_event |
Character. If |
which_form |
Character. If |
wide |
Logical. If |
Value
A list with elements:
- data
Transformed data. With
final_format = "by_event"or"by_form", as inrd_split(): a tibble with one row per event or form and its dataset in the list-columndf(e.g.trans$data$df[[1]]), or thedata.frameof the event or form chosen withwhich_eventorwhich_form.- dictionary
Updated dictionary data.frame.
- event_form
Event–form mapping (if applicable).
- results
Character summary of transformation steps performed.
See Also
Other process functions:
rd_checkbox(),
rd_dates(),
rd_delete_vars(),
rd_dictionary(),
rd_factor(),
rd_insert_na(),
rd_recalculate(),
rd_rlogic(),
rd_split()
Examples
# Minimal usage (project object or data + dictionary)
trans <- rd_transform(covican)
# Custom checkbox labels
trans <- rd_transform(covican,
checkbox_labels = c("Not present", "Present"))
# Return only a single form (wide)
trans <- rd_transform(covican,
final_format = "by_form",
which_form = "laboratory_findings",
wide = TRUE)
Recalculate REDCap Calculated Fields
Description
This function recalculates each calculated field if the logic can be transcribed to R. Note that calculated fields containing smart variables, or variables of another repeating instrument or repeating event without their instance, cannot be transcribed (the variables of other events, e.g. [visit_2_arm_1][weight], and [event][field][current-instance] can).
The function returns the dataset and dictionary with the recalculated variables appended (named as the original field plus _recalc), along with a summary table of the recalculation results.
Usage
recalculate(data, dic, event_form = NULL, exclude_recalc = NULL)
Arguments
data |
Data frame containing data from REDCap. |
dic |
Data frame containing the dictionary read from REDCap. |
event_form |
Data frame containing the correspondence of each event with each form. |
exclude_recalc |
Character vector with the names of the variables that should not be recalculated. Useful for projects with time-consuming recalculations for certain calculated fields. |
Read REDCap data
Description
Import REDCap data into R either from REDCap's exported R file or directly via the REDCap API. The function returns a list with the dataset, the project dictionary (metadata) and, for longitudinal projects, the instrument–event mapping (event_form) when available.
Usage
redcap_data(
data_path = NA,
dic_path = NA,
event_path = NA,
uri = NA,
token = NA,
sep = ",",
filter_field = NULL,
survey_fields = FALSE,
rm_mdc = TRUE,
mdc = NULL
)
Arguments
data_path |
Path to exported R file (use with |
dic_path |
Path to the dictionary file (CSV or XLSX; use with |
event_path |
Path to the event-form mapping file (CSV or XLSX) for longitudinal projects (downloadable via the |
uri |
REDCap API base URI (use with |
token |
REDCap API token (use with |
sep |
Character string specifying the field separator for the exported dictionary CSV file. Default |
filter_field |
Optional character vector of field names to request from the API. It must include the record
identifier (the first field of the project, e.g. |
survey_fields |
Logical; include survey-related fields when pulling via API. Default |
rm_mdc |
Logical. Remove Missing Data Codes (default |
mdc |
Optional Missing Data Codes of the project, besides the default ones of REDCap ( |
Details
Two import modes are supported:
-
Exported files — use
data_path(REDCap R export) anddic_path(dictionary CSV/XLSX). -
API — use
uriandtokento pull data and metadata directly from REDCap.
If the project is longitudinal, provide event_path (instrument–event mapping)
or the function will attempt to fetch it from the API when using API mode.
With the API, the metadata of the project (dictionary, project information, events, instruments, ...) and the
records are read with several requests: the values and their labels are read separately (in batches of records,
and the labels again if the records changed). The record identifiers are read as text in
all of them (long identifiers such as 9007199254740993, or 100000000000000, are not changed), and the
identifier is a number only when its text is that number, as with the exported files. The labels of the events
(redcap_event_name.factor), repeated instruments and data access groups are given to each row by its code (the
unique event name, instrument or data access group), and they are checked with the metadata of the project (its
events, arms, instruments and data access groups): if the records changed between the values and the labels, the labels are
read again, and the function stops if they keep changing. When that metadata can't be read, those columns have
the codes instead of the labels, with a warning (except a single code with a single label in all the rows, e.g. the
data access group of a user assigned to a group).
Steps for using exported data in REDCap:
Use the REDCap Export Data function and choose R Statistical Software format.
REDCap generates:
A CSV file with observations.
An R script to format variables for import.
Keep the R script and its CSV file in the same directory (the script reads the CSV from its folder). The dictionary and the event mapping can be in other folders.
Value
A list with:
-
data: Imported dataset. -
dictionary: Variable dictionary (project meta data). -
event_form: Event-form mapping for longitudinal projects (if applicable).
Note
With the exported files, dic_path is required to load the project dictionary (with the API, the dictionary is
read from REDCap).
Use either exported-files mode (
data_path+dic_path) or API mode (uri+token) — not both.For exported files, REDCap's R export is required for
data_path. Dictionary and event files must be CSV or XLSX.
Examples
## Not run:
# From exported files
out <- redcap_data(
data_path = "project_export.r",
dic_path = "project_dictionary.csv",
event_path = "instrument_event_map.csv"
)
# From API
out_api <- redcap_data(
uri = "https://redcap.example.org/api/",
token = "REPLACE_WITH_TOKEN"
)
## End(Not run)
Creation of a Data Frame with Variables from All Forms of a Specified Event
Description
This function generates a nested dataset filtered by each event, containing only the variables associated with each event. It uses the provided data, dictionary, and event-form mapping. You can choose to return data for a specific event.
Usage
split_event(data, dic, event_form, which = NULL)
Arguments
data |
Data frame containing data from REDCap. |
dic |
Data frame containing the dictionary read from REDCap. |
event_form |
Data frame containing the correspondence of each event with each form. |
which |
Character string specifying an event if only data for that event is desired. |
Creation of a Data Frame with Variables from a Specified Form
Description
This function generates a nested dataset containing only the variables associated with each form, using the provided data, dictionary, and event-form mapping. You can choose to return data for a specific form.
Usage
split_form(data, dic, event_form = NULL, which = NULL, wide = FALSE)
Arguments
data |
Data frame containing data from REDCap. |
dic |
Data frame containing the dictionary read from REDCap. |
event_form |
Data frame containing the correspondence of each event with each form. |
which |
Character string specifying a form if only data for that form is desired. |
wide |
Logical indicating if the dataset should be returned in a wide format ( |
Convert Variables to Factors
Description
This function converts all variables in the dataset to factors, except those specified in the exclude parameter.
Usage
to_factor(data, dic, exclude = NULL)
Arguments
data |
Data frame containing the REDCap data. |
dic |
Data frame containing the REDCap dictionary. |
exclude |
Character vector specifying the names of variables that should not be converted to factors. If |
Transformation of Checkboxes with Branching Logic
Description
This function inspects all the checkboxes in the study to determine if they have a branching logic. If a branching logic is present and its result is missing, the function will input a missing value into the checkbox. If checkbox_na is TRUE, the function will additionally input a missing value when the branching logic isn't satisfied, not just when it is missing. If a branching logic cannot be found or the logic cannot be transcribed due to the presence of smart variables, the variable is added to a list of reviewable variables that will be printed.
The function returns the dataset with the transformed checkboxes and a table summarizing the results.
Usage
transform_checkboxes(data, dic, event_form = NULL, checkbox_na = FALSE)
Arguments
data |
Data frame containing data from REDCap. |
dic |
Data frame containing the dictionary read from REDCap. |
event_form |
Data frame containing the correspondence of each event with each form. |
checkbox_na |
Logical indicating if values of checkboxes with branching logic should be set to missing only when the branching logic is missing ( |