Last Updated: February 25, 2016
·
3.759K
· dionysios

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");}
}