Use switch() instead of ifelse() to return a NULL

February 21, 2017
By

(This article was first published on http://r-addict.com, and kindly contributed to R-bloggers)

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

statement <- length(character()) > 0
statement
[1] FALSE

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

if (statement) {
   res <- "message"
} else {
   res <- NULL
}
res
NULL

or use simplified interface with ifelse() function

ifelse(statement, "message", NULL)
Error in ifelse(statement, "message", NULL): replacement has length zero

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

switch(statement + 1, NULL, "message")
NULL

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

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

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)