0

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)
zx8754
  • 52,746
  • 12
  • 114
  • 209
Ray Kodiak
  • 69
  • 1
  • 13

2 Answers2

1

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))
Jonathan Carroll
  • 3,897
  • 14
  • 34
0

We can do this without filtering

FINAL %>% 
     mutate(N = as.integer(is.na(NAME)),
            C = as.integer(is.na(COUNTRY)),
            K = as.integer(CATEGORY == 'T' & (BEGN_DT <= 20170302 & END_DT >= 20170312)))

It will result in binary columns with 1 corresponding to TRUE values for the condition and 0 for other cases.

akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    thanks Ya'All! Interesting to see how different people brains work, I wish there was a way to flag negative people, they suck or at least remove them from helping on my post. – Ray Kodiak Feb 08 '17 at 23:51