if/else in R scripts
A common misconception is that the "else" part of an if/else statement can be either on the same line as the "if" statement, or on a subsequent line.
It turns out that R runs the script as if it was written in the command line: if the two parts are in two different lines, this will produce an error.
if(test){cat("if");}
else{cat("else");} #error: unexpected 'else'
if(test){cat("if");} else{cat("else");} #no errors
If one does not wish to put everything in one line, putting both sub-statements in a block will also work:
{
if(test){cat("if");}
else{cat("else");}
}
Written by Dionysios Barmpoutis
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#R
Authors
Related Tags
#r
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#