OuhscBbmc / REDCapR

R utilities for interacting with REDCap
https://ouhscbbmc.github.io/REDCapR
Other
112 stars 45 forks source link

Fetature Request: function to convert standard race Q to a single variable with a multiple races output #520

Open higgi13425 opened 2 months ago

higgi13425 commented 2 months ago

A function to make race into a single variable would be a big help.

A solution is proposed below.

I built a function for converting the standard REDCap race categories into a single variable with an option for multiple races.

This depends on using standard redcap race Q using a standard subject_id variable

wondering if you could test this out

singlevar_race <- function(data) {  
data |>  pivot_longer(cols = race___1:race___7,                
      names_to = "race_num",                
      names_prefix = "race___",               
       values_to = "true") |>  
      ilter(true == 1) |>   
      arrange(subject_id) |>   
      mutate(lead = lead(subject_id)) |>   
      mutate(race_num = case_when(            
      subject_id == lead ~ "8",            
      TRUE ~ race_num)) |>     
      distinct(subject_id, .keep_all = TRUE) |>     
      mutate(race = case_when(      
      race_num == '1' ~ "American Indian or Alaska Native",       
      ace_num == '2' ~ "Asian",      
      race_num == '3' ~ "Black or African American",      
      race_num == '4' ~ "Native Hawaiian or Other Pacific Islander",               race_num == '5' ~ "Not Reported",      
            race_num == '6' ~ "Unknown",      
            race_num == '7' ~ "White",      
            race_num == '8' ~ "Multiple Races")) |>     
            select(-true, -lead)
}

Expected behavior: This would create two variables, race_num, and race, that would be added on to standard REDCap datasets with mutate

Peter