Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in R Programming by (5.3k points)
edited by

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
edited by

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

Browse Categories

...