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

Thomas Lumley tlumley at u.washington.edu
Mon Mar 7 17:36:50 CET 2005


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