Skip to content

Copenhagen: Code simplification with if_any #22

@JoaodcPires

Description

@JoaodcPires

Simplify this code

# Start with linelist:
linelist <- linelist %>% 
  
  # Create a new column called gastrosymptoms:
  mutate(gastrosymptoms = case_when(
    
    # gastrosymptoms = FALSE if none of the gastro columns are TRUE:
    if_all(.cols = all_of(gastro_cols), 
           .fns = ~ !. %in% c(TRUE)) ~ FALSE,
    
    # gastrosymptoms = TRUE if any of the gastro columns are TRUE:
    if_any(.cols = any_of(gastro_cols), 
           .fns = ~ . == TRUE) ~ TRUE
    
  ))

Users were confused about the use of if_all and if_any. In this case, if_all is not necessary because we are looking for individuals that have any of the case definition symptoms.

Suggestion with more documentation:

# Simplified code
linelist <- linelist %>% 
  
  # Create a new column called gastrosymptoms:
  mutate(gastrosymptoms = case_when(
    
    # gastrosymptoms = TRUE if any of the gastro columns are TRUE:
    # we could use if_all if we would like to consider only people that have all of the symptoms
    
    # specify the columns with the gastro_cols vector
    if_any(.cols = any_of(gastro_cols), 
           
           # specify the function which will be evaluated with case_when with .fns
           # ~ transforms the following input to a function to be evaluated.
           # the dot . here signifies columns specified in .cols
           .fns = ~ . == TRUE) ~ TRUE,  
    
    # All others rows are FALSE as these individuals do not have any of the symptoms in gastro_cols
    TRUE ~ FALSE
    
))

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentationenhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions