[Rd] parse error with if else (PR#9551)

murdoch at stats.uwo.ca murdoch at stats.uwo.ca
Tue Mar 6 19:35:35 CET 2007


On 3/6/2007 12:15 PM, Stephanie.Mahevas at ifremer.fr wrote:
> Full_Name: Stephanie MAHEVAS
> Version: 2.4.1
> OS: Windows NT
> Submission from: (NULL) (134.246.55.50)
> 
> 
> 
> the two following instructions provide a synthax  error :
> 
> if ( 5 > 4 ) cat("ok1")
> else cat("ok2")
> 
> and
> 
> if ( 5 > 4 ){ cat("ok1")}
> else cat("ok2")
> 
> whereas these ones don't
> 
> if ( 5 > 4 ) cat("ok1") else cat("ok2")
> 
> and
> 
> if ( 5 > 4 ){ cat("ok1")
> }else cat("ok2")
> 
> It looks like a parser problem. If else is not on the same line as if or if the
> end of block statement of if } is not paste to else, else does not seem linked
> with if

This is a documented "feature" of the language, not a bug.  (See the 
language guide, section 3.2.1 "if", around the 4th paragraph.)

It arises because R tries to evaluate a statement as soon as it is 
complete, and

if ( 5 > 4 ) cat("ok1")

is a complete statement.  You can get the behaviour you want by wrapping 
the whole think in curly brackets so that R doesn't start evaluating too 
early, e.g.

 > {
+  if ( 5 > 4 ) cat("ok1")
+  else cat("ok2")
+ }
ok1>

Duncan Murdoch



More information about the R-devel mailing list