[R] Got "Unexpected ELSE error"

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Wed Jun 20 12:05:32 CEST 2007


Shiazy Fuzzy wrote:
> Dear R-users,
>
> I have a problem with the IF-ELSE syntax.
> Please look at the folllowing code and tell me what's wrong:
>
> a <- TRUE
> if ( a )
> {
>         cat("TRUE","\n")
> }
> else
> {
>         cat("FALSE","\n")
> }
>
> If I try to execute with R I get:
>      Error: syntax error, unexpected ELSE in "else"
> The strange thing is either "cat" instructions are executed!!
>   
For some odd reason this is not actually a FAQ...

It is an anomaly of the R (and S) language (or maybe a necessary
consequence of its interactive usage) that it tries to complete parsing
of expressions as soon as possible, so 

2 + 2
+ 5

prints "4" and then "5", whereas

2 + 2 +
5

prints "9".  Similarly, when encountered on the command line,

if (foo) bar

will result in the value of bar if foo is TRUE and otherwise NULL. A
subsequent

else baz

will be interpreted as a new expression, which is invalid because it
starts with "else". To avoid this effect you can either move the "else"
to the end of the previous line, or put braces around the whole if
construct. I.e.

if (foo) {
    bar
} else {
    baz
}

or

if (foo) bar else baz

or

{
    if (foo)
         bar
    else
         baz
}

should all work.

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list