stRoke/R/read_redcap_tables.R

72 lines
2.2 KiB
R
Raw Normal View History

#' Download REDCap data
#'
2023-01-11 12:54:08 +01:00
#' Wrapper function for using REDCapR::redcap_read and REDCapRITS::REDCap_split
#' including some clean-up. Works with longitudinal projects with repeating
#' instruments.
#' @param uri REDCap database uri
#' @param token API token
#' @param records records to download
#' @param fields fields to download
#' @param events events to download
#' @param forms forms to download
2023-01-11 12:54:08 +01:00
#' @param generics vector of auto-generated generic variable names to
#' ignore when discarding empty rows
#'
#' @return list of instruments
#' @export
#'
#' @examples
#' # Examples will be provided later
2022-12-21 07:29:23 +01:00
read_redcap_tables <- function(uri,
2023-01-12 13:44:29 +01:00
token,
records = NULL,
fields = NULL,
events = NULL,
forms = NULL,
generics = c(
"record_id",
"redcap_event_name",
"redcap_repeat_instrument",
"redcap_repeat_instance"
)) {
# Notes to self: Based on the metadata, this functionality could be
# introduced without using the REDCapRITS package.. To be tried..
2023-01-12 13:44:29 +01:00
d <- REDCapR::redcap_read (
redcap_uri = uri,
token = token,
fields = fields,
events = events,
forms = forms,
records = records
)
2023-01-12 13:44:29 +01:00
m <-
REDCapR::redcap_metadata_read (redcap_uri = uri, token = token)
2022-12-21 12:20:29 +01:00
if (requireNamespace("REDCapRITS", quietly = TRUE)) {
2023-01-12 13:44:29 +01:00
l <- REDCapRITS::REDCap_split(d$data,
m$data[m$data$field_name %in% names(d$data),],
2023-01-11 12:54:08 +01:00
forms = "all")
2022-12-21 12:20:29 +01:00
} else {
cli::cli_abort(
2023-01-12 13:44:29 +01:00
c(
"x" = "The package REDCapRITS is not installed.",
"i" = "Please install REDCapRITS by running
\"remotes::install_github('agdamsbo/REDCapRITS')\"."
)
2022-12-21 12:20:29 +01:00
)
}
2023-01-12 13:44:29 +01:00
lapply(l, function(i) {
if (ncol(i) > 2) {
s <- data.frame(i[, !colnames(i) %in% generics])
i[!apply(is.na(s), MARGIN = 1, FUN = all),]
} else {
i
}
})
2022-12-21 12:20:29 +01:00
}