[R] How "else" works

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Wed Feb 12 00:13:03 CET 2003


Brian.J.GREGOR at odot.state.or.us writes:

> 	if(cond){
> 		cons.expr
> 	}
> 	else alt.expr
> 
> This results a syntax error.
> 
> Am I doing something wrong, or doesn't R support the spanning of the
> combination of if and else statements over several lines?

The rule is that in it read-eval-print loop, R will evaluate as soon
as an expression is syntactically complete. Consider these two
examples:

(1)
if (x == y) print("equal")
b <- log(x)

and

(2)
if (x == y) print("equal")
else print("not equal")

The problem is that in (1), you want output after reading the first
line, and in the other, you don't. However, after reading the first
line you cannot know which type of example you have. So R assumes it
is of type (1), and that a new expression starts on the next line.
However, an expression cannot begin with "else", hence you get a
syntax error in case (2).

The way out is to ensure that the first line remains incomplete, so

if (x == y) print("equal") else 
print("not equal")

if (x == y) 
print("equal") else print("not equal")

{if (x == y) print("equal")
else print("not equal")}

all work.

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list