rdplyrextra

combine dyplr criteria code?


I have this code that works well, but how can I combine the 3 lines of code into 1 ?

Basically I need to create these extra helper QC columns, I am also translating this from other SAS code (that someone else owns) to R, the goal is to just translate it, not to question it.

The goal is to end up with 3 extra columns N, C and K appending to the end of the data set, when their condition is satisfied.

TEST <- FINAL %>% filter(is.na(NAME)) %>% mutate(N = 1)

TEST <- FINAL %>% filter(is.na(COUNTRY)) %>% mutate(C = 1)

TEST <- FINAL %>% filter( CATEGORY == 'T' & (BEGN_DT <= 20170302 & END_DT >= 20170312) ) %>% mutate(K = 1)

Solution

  • Conditional mutate is still a work-in-progress for dplyr, but it can be done:

    mtcars %>%
      mutate(x = case_when(.$cyl == 6 ~ 1)) %>% 
      mutate(y = case_when(.$am == 1 ~ 9)) %>% 
      mutate(z = case_when(is.na(.$x) ~ 5))