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

Gabor Grothendieck ggrothendieck at myway.com
Mon Mar 7 17:17:43 CET 2005


Jan T. Kim <jtk <at> cmp.uea.ac.uk> writes:

: 
: 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.
: 

If it did not work that way it would require console lookahead.  That is 
it would not know that the if statement was finished and would have
to wait for the following statement to be completely typed in before
it could process the if.  The way it works now the if statement can
be processed immediately.




More information about the R-help mailing list