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

roger bos roger.bos at gmail.com
Mon Mar 7 17:49:10 CET 2005


Thanks to everyone who took the time to point out the simple error. 
You would not think I have been programming in R/S for over a year. 
Could it be that the code works when enclosed in a function?  I tested
my code and it worked previously, but I was running it line by line
and discovered my syntax error.

Thanks again.

Roger



On Mon, 7 Mar 2005 08:36:50 -0800 (PST), Thomas Lumley
<tlumley at u.washington.edu> wrote:
> On Mon, 7 Mar 2005, 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:
> 
> Other people have told you how to fix this.  I will point out in addition
> that if...else is not different syntax for ifelse() but a very different
> construct.
> 
> ifelse() is a function that operates on vectors and returns a vector that
> is always the same length as the first argument. It does not change the
> flow of execution: all three of the arguments are evaluated.
> 
> if(){} else {} chooses which branch of code to evaluate based on a single
> logical value.  The value returned by this expression could be of
> completely different length and type depending on which code was
> evaluated.
> 
> It might also be worth noting that the behaviour of newlines in
> terminating if() {} expressions is unavoidable in an interpreter using
> this syntax. When the user types
> 
> if(condition){
>    some.code()
> }
> 
> the interpreter cannot possibly tell whether an `else' clause is coming.
> Avoiding the problem would require a fairly significant change to the
> language, not just to the parser, eg adding an endif (the shell script
> solution), or requiring parentheses around the whole expression (the LISP
> solution, and in a sense the Python solution, though there the parentheses
> are invisible)
> 
> 
>        -thomas
>




More information about the R-help mailing list