[R] simple if...else causes syntax error

Jan T. Kim jtk at cmp.uea.ac.uk
Mon Mar 7 17:46:49 CET 2005

On Mon, Mar 07, 2005 at 10:16:50AM -0500, roger bos wrote:
> I am trying to do the simplest thing in the world.  The following works:
> aaa <- ifelse(aaa==5, 6, 7)            
> But if I want to change the if...else syntax instead, it gives errors
> and assigns 7 to aaa.  Here is the problem code:
> aaa <- 5
> if ( aaa==5 ) { 
>    aaa <- 6
> }
> else {
>    aaa <- 7
> }

This is due to R's (somewhat peculiar) semantics of newline, which R
interprets as a terminator if an expression can terminate at the position
of the newline, or else as a plain whitespace, see section on "Separators"
in the R Language Definition. In the construction

    if ( aaa==5 ) {
       aaa <- 6

R decides that the final newline can be a terminator, namely of an if-
expression without an else branch. So, the if-expression is consumed
by the parser and "forgotten" for the purpose of associating the else
branch with it. The else branch thus appears to be astray and is reported
as a syntax error.

All this does not happen if the entire construct is enclosed in braces.
Alternatively, the "else" can be placed on one line with the brace closing
the if branch.

Out of personal interest: Does anyone here know why the R parser was
designed this way? Personally, I have been coding in R for years in the
belief that newline is whitespace, and never even noticed any problems
because all my ifs with elses were within functions and thus enclosed
in curly braces.

Best regards, Jan
 +- Jan T. Kim -------------------------------------------------------+
 |    *NEW*    email: jtk at cmp.uea.ac.uk                               |
 |    *NEW*    WWW:   http://www.cmp.uea.ac.uk/people/jtk             |
 *-----=<  hierarchical systems are for files, not for humans  >=-----*

More information about the R-help mailing list