[R] Re: if .. else parse error {was "Sweave question"} (fwd)

Rafael A. Irizarry ririzarr at jhsph.edu
Thu Dec 25 21:38:54 CET 2003


Dear All,

Thanks to all that took the time to respond to my questions (included 
at the bottom). Martin Maechler was nice enough to give me a detailed 
explanation which he suggested i forward. 

The confusion arose because

if(exists("x"))	plot(x,x)
else{ plot(1,1,type="n");text(1,1,"data not available.\n")}

gave me an error when used as a chunk in a Sweave document but the 
same code didnt give me errors inside a function:

a <- function(){
if(exists("x"))  plot(x,x) 
else{  plot(1,1);  print("hello")}
}
a()

As pointed out by some of the responeders,  the problem is that in the  
original code the first two lines were syntactically complete which 
results in a line starting with an else, resulting in an error 
regardless of Sweave. But this only happens if the 
if-else statement is at top-level (in the function version it isnt)

Martin explains in more detail:

M>Remember the *reason* why it can't work on top level:
M>- At the end of the line, the S parser will evaluate the current
M>  statement  __ if it is complete __
M>  This is true for   "if (A)  B" or also  "if (A) { B ; C }"
M>  when a next line starts with "else D",
M>  this is invalid :  S language expressions cannot start with 'else'.
M>
M>  => consequence:  
M>     Make sure the if() part of an  "if(A) B else C " is not
M>     after B, because it's then interpreted as an  "if(A) B" .
M>
M>You never have this problem if all of this is part of an
M>enclosing expression, because parsing will only end after
M>completing the outermost expression; in the case of functions
M>this is the full (outermost) function body.

for example:
{
if(exists("x"))  plot(x,x)
else{ plot(1,1);print("hello")}
}
does not give errors.

An easy way to avoid this error is to follow this suggestion from the if 
help page:

"For that reason, one (somewhat extreme) attitude of defensive
 programming uses braces always, e.g., for 'if' clauses.
 always enclose expressions in 
 if-else statements even if you dont think you need them."


thanks again,
-r

"Rafael A. Irizarry" <ririzarr at jhsph.edu> writes:
                                                                                                                                          
> Using Sweave in the tools library (R version 1.8.0: sorry i havent
> upgraded), it seems i cant use if statements in R chunks that make 
graphs.
> i have this:
>
> <<fig=TRUE,echo=F>>=
> par(mfrow=c(1,1))
> if(exists("x"))
>       plot(x,x)
> else{
>   plot(1,1,type="n")
>   text(1,1,"data not available.\n")
> }
> @
>
> and I get this error:
>
> Error:  chunk 6
> Error in parse(file, n, text, prompt) : parse error
>
> any help is appreciated.
>
> thanks and apologies if this not a problem in R 1.8.1
> rafael
>




More information about the R-help mailing list