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. %>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression.
The pipe operator is a special operational function available under the magrittr and dplyr package (basically developed under magrittr), which allows us to pass the result of one function/argument to the other one in sequence. It is generally denoted by symbol %>% in R Programming.
In RStudio the keyboard shortcut for the pipe operator %>% is Ctrl + Shift + M (Windows) or Cmd + Shift + M (Mac). In RStudio the keyboard shortcut for the assignment operator <- is Alt + - (Windows) or Option + - (Mac).
Pipes are an extremely useful tool from the magrittr package 1 that allow you to express a sequence of multiple operations. They can greatly simplify your code and make your operations more intuitive. However they are not the only way to write your code and combine multiple operations.
Here is a quick example that takes advantage of the .
and ifelse
:
X<-1 Y<-T X %>% add(1) %>% { ifelse(Y ,add(.,1), . ) }
In the ifelse
, if Y
is TRUE
if will add 1, otherwise it will just return the last value of X
. The .
is a stand-in which tells the function where the output from the previous step of the chain goes, so I can use it on both branches.
Edit As @BenBolker pointed out, you might not want ifelse
, so here is an if
version.
X %>% add(1) %>% {if(Y) add(.,1) else .}
Thanks to @Frank for pointing out that I should use {
braces around my if
and ifelse
statements to continue the chain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With