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

From: Thomas Lumley <tlumley_at_u.washington.edu>
Date: Tue 08 Mar 2005 - 03:36:50 EST

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



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Tue Mar 08 03:48:53 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:30:41 EST