Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add make_yes_no() and make_yes_no_unknown() functions #38

Open
wdefreitas opened this issue Nov 3, 2022 · 2 comments
Open

Add make_yes_no() and make_yes_no_unknown() functions #38

wdefreitas opened this issue Nov 3, 2022 · 2 comments
Assignees
Labels
enhancement New feature or request
Milestone

Comments

@wdefreitas
Copy link
Collaborator

This function in combination with the below dplyr step will find all variables with a yes or checked answer and convert them into relevelled factors with only two or three levels, depending on make_yes_no() or make_yes_no_unknown() functions.

make_yes_no <- function(x) {
  if(is.factor(x)){
  factor(case_when(
    str_detect(x, fixed("yes", ignore_case = TRUE)) == TRUE ~ "Yes",
    str_detect(x, fixed("checked", ignore_case = TRUE)) == TRUE ~ "Yes",
    TRUE ~ "No or Unknown"
  )
  )} else{
    x
  }
}

make_yes_no_unknown <- function(x) {
  if(is.factor(x)){
  factor(case_when(
    str_detect(x, fixed("yes", ignore_case = TRUE)) == TRUE ~ "Yes",
    str_detect(x, fixed("checked", ignore_case = TRUE)) == TRUE ~ "Yes",
    str_detect(x, fixed("no", ignore_case = TRUE)) == TRUE ~ "No",
    str_detect(x, fixed("unchecked", ignore_case = TRUE)) == TRUE ~ "No",
    TRUE ~ "Unknown"
  )
  )} else{
    x
  }
}

df |>
select(record_id, ... , where(~ any(grepl('Yes|Checked', .)))) |> 
  mutate(across(.cols=everything(), make_yes_no_unknown)) 
@wdefreitas wdefreitas added the enhancement New feature or request label Nov 3, 2022
@wdefreitas wdefreitas self-assigned this Nov 3, 2022
@RaymondBalise
Copy link
Owner

RaymondBalise commented Dec 21, 2022

fixed( ) conflicts between stringr and recipies. The code below is more bullet proof. It makes sure that strings start with yes or start with checked.

make_yes_no <- function(x) {
  if(is.factor(x) | is.character(x)){
  factor(case_when(
      str_detect(x, regex("^yes", ignore_case = TRUE)) == TRUE ~ "Yes",
      str_detect(x, regex("^checked", ignore_case = TRUE)) == TRUE ~ "Yes",
    TRUE ~ "No or Unknown"
  )
  )} else{
    x
  }
}

@RaymondBalise
Copy link
Owner

throw an error if values are yes/no/checked/unchecked

@RaymondBalise RaymondBalise added this to the Version 1.1 milestone Feb 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants