Skip to content

New feature: update data dictionary for multiple choice checkbox variables. #598

Description

@RoryChenXY

A function I wrote for my own project and thought this could be useful:

expand_checkbox_dictionary <- function(dict,
                                       var_col = "field_name",
                                       type_col = "field_type",
                                       label_col = "field_label",
                                       choice_col = "select_choices_or_calculations") {
  
  dict_updated <- dict |>
    dplyr::mutate(.row_id = dplyr::row_number()) |>
    dplyr::group_split(.row_id, .keep = TRUE) |>
    purrr::map_dfr(function(row) {
      
      if (row[[type_col]] != "checkbox") {
        return(dplyr::select(row, -.row_id))
      }
      
      choices <- REDCapR::checkbox_choices(row[[choice_col]])
      
      if (nrow(choices) == 0) {
        return(dplyr::select(row, -.row_id))
      }
      
      out <- row[rep(1, nrow(choices)), ] |>
        dplyr::bind_cols(choices) |>
        dplyr::mutate(
          !!var_col := paste0(.data[[var_col]], "___", id)
        )
      
      if (!is.null(label_col) && label_col %in% names(out)) {
        out <- out |>
          dplyr::mutate(
            !!label_col := paste0(.data[[label_col]], "_", label),
            !!type_col := "yesno"
          )
      }
      
      out |>
        dplyr::select(-.row_id) |>
        dplyr::select(-id, -label)
      
    })
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions