On Tue, 2005-07-12 at 16:22 +0200, ecoinfo wrote:
> Hi R users,
>  Maybe the question is too simple.
>  In a IF ... ELSE ... statement "if(cond) cons.expr else alt.expr", IF and 
> ELSE should be at the same line? 
> For example,
>  if (x1==12)
> {
> y1 <- 5 
> }else
> {
> y1 <- 3
> }
>  is right, while
>  if (x1==12)
> {
> y1 <- 5 
> }
> else # Error: syntax error
> {
> y1 <- 3
> }
>  is wrong? 
>  Thanks

Note the following from the Details section of ?"if"

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


One other approach is the following:

if (x1 == 12) 
{
  y1 <- 5 
} else {
  y1 <- 3
}

Note the presence of both braces on the 'else' line.

HTH,

Marc Schwartz

______________________________________________
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

Reply via email to