Here you will find daily news and tutorials about R, contributed by over 750 bloggers.
There are many ways to follow us - By e-mail:On Facebook: If you are an R blogger yourself you are invited to add your own R content feed to this site (Non-English R bloggers should add themselves- here)

Have you ever tried to return a NULL with the ifelse() function? This function is a simple vectorized workflow for conditional statements. However, one can’t just return a NULL value as a result of this evaluation. Check a tricky workaround solution in this post.

Imagine a simple R logical statement like

and depending on that logical value you would like to create a new variable called res. You can follow a regular if conditional statement

or use simplified interface with ifelse() function

However it looks like one is not able to return the NULL as a result of this operation.

A solution is to jump to the other conditional function called switch(), which for the first parameter takes number (n) and returns the value passed as the n-th parameter. If one treats logical values as TRUE is 1 and FALSE is 0 then primary ifelse() statement can be rebuild to switch() call like

What do you think about such workaround? Do you use other solutions for such a situation?

Related

To leave a comment for the author, please follow the link and comment on their blog: http://r-addict.com.