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

Martin Maechler maechler at stat.math.ethz.ch
Tue Dec 23 18:22:25 CET 2003


>>>>> "Rafael" == Rafael A Irizarry <ririzarr at jhsph.edu>
>>>>>     on Tue, 23 Dec 2003 10:44:38 -0500 (EST) writes:

    Rafael> Using Sweave in the tools library (R version 1.8.0:
    Rafael> sorry i havent upgraded), it seems i cant use if
    Rafael> statements in R chunks that make graphs.  i have
    Rafael> this:

    Rafael> <<fig=TRUE,echo=F>>=
    Rafael> par(mfrow=c(1,1))
    Rafael> if(exists("x")) 
    Rafael>    plot(x,x)
    Rafael> else{
    Rafael>    plot(1,1,type="n")
    Rafael>    text(1,1,"data not available.\n")
    Rafael> }
    Rafael> @

    Rafael> and I get this error:

    Rafael> Error:  chunk 6
    Rafael> Error in parse(file, n, text, prompt) : parse error


This has nothing to do with Sweave;
it's a famous "beginner"s (;-) mistake:

?if   has the explanation :

 if> Note that it is a common mistake to forget putting braces ('{ ..}') 
 if> around your statements, e.g., after 'if(..)' or 'for(....)'.
 if> In particular, you should not have a newline between '}' and 
 if> 'else' to avoid a syntax error in entering a 'if ... else'
 if> construct at the keyboard or via 'source'. For that reason, one
 if> (somewhat extreme) attitude of defensive programming uses braces
 if> always, e.g., for 'if' clauses.

Regards,
and Merry Christmas to all R-help readers!
Martin




More information about the R-help mailing list