Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Conditional evaluation when using the pipe operator %>%

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?

like image 877
rmf Avatar asked Jun 02 '15 18:06

rmf


People also ask

What does %>% do on R?

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.

How does the %>% pipe work in R?

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.

How do you type a pipe operator in R?

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).

What does the pipe function do in R?

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.


1 Answers

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.

like image 197
John Paul Avatar answered Oct 31 '22 00:10

John Paul