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

From: Jan T. Kim <jtk_at_cmp.uea.ac.uk>
Date: Tue 08 Mar 2005 - 03:46:49 EST

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 ifexpression  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@cmp.uea.ac.uk                               |
 |    *NEW*    WWW:   http://www.cmp.uea.ac.uk/people/jtk             |
 *-----=<  hierarchical systems are for files, not for humans  >=-----*

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Received on Tue Mar 08 03:07:23 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:30:41 EST