R/bind_tibbles.R

Defines functions bind_tibbles

Documented in bind_tibbles

#' @title
#' Extract data tibbles from a REDCapTidieR supertibble and bind them to an
#' environment
#'
#' @description
#' Take a supertibble generated with `read_redcap()`
#' and bind its data tibbles (i.e. the tibbles in the `redcap_data` column) to
#' an environment. The default is the global environment.
#'
#' @returns
#' This function returns nothing as it's used solely for its side effect of
#' modifying an environment.
#'
#' @param supertbl A supertibble generated by `read_redcap()`. Required.
#' @param environment The environment to bind the tibbles to. Default is
#' `rlang::global_env()`.
#' @param tbls A vector of the `redcap_form_name`s of the data tibbles to bind to
#' the environment. Default is `NULL` which binds all data tibbles.
#'
#' @examples
#' \dontrun{
#' # Create an empty environment
#' my_env <- new.env()
#'
#' ls(my_env)
#'
#' superheroes_supertbl
#'
#' bind_tibbles(superheroes_supertbl, my_env)
#'
#' ls(my_env)
#' }
#' @export

bind_tibbles <- function(supertbl,
                         environment = global_env(),
                         tbls = NULL) {
  check_arg_is_supertbl(supertbl, req_cols = "redcap_data")
  check_arg_is_env(environment)
  check_arg_is_character(tbls, null.ok = TRUE, any.missing = FALSE, min.len = 1)

  # Name variables
  my_supertbl <- supertbl

  # Apply conditional loading for specific instruments
  if (!is.null(tbls)) {
    my_supertbl <- my_supertbl %>%
      filter(.data$redcap_form_name %in% tbls)
  }

  table_names <- my_supertbl$redcap_form_name

  # Map over table names and environment data to load into environment
  map2(
    .x = table_names,
    .y = my_supertbl$redcap_data,
    .f = ~ env_poke(
      env = environment,
      nm = .x,
      value = .y
    )
  )
  return(invisible(NULL))
}

Try the REDCapTidieR package in your browser

Any scripts or data that you put into this service are public.

REDCapTidieR documentation built on April 3, 2025, 10:50 p.m.