atoxvg
Last Updated: February 25, 2016
·
470
· dionysios
083618effe3fca9cd4ecc895809833a8

if/else in R scripts

r

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