0 votes
1 view
in R Programming by (5k points)

When using the pipe operator %>% with packages such as dplyr, ggvis, dycharts, etc, how do I do a step conditionally? For example;

step_1 %>%

step_2 %>%

if(condition)

step_3

These approaches don't seem to work:

step_1 %>%

step_2 

if(condition) %>% step_3

step_1 %>%

step_2 %>%

if(condition) step_3

There is a long way:

if(condition)

{

step_1 %>%

step_2 

}else{

step_1 %>%

step_2 %>%

step_3

}

Is there a better way without all the redundancy?

1 Answer

0 votes
by (23.6k points)

You can use the  if-else statement with the pipe operator as follows:

library("magrittr")

 X<-1

 Y<-T

 X %>% 

   add(1) %>% 

   {if(Y) add(.,1) else .}

[1] 3

...