Re: [R] question for IF ELSE usage

From: Marc Schwartz (via MN) <mschwartz_at_mn.rr.com>
Date: Wed 13 Jul 2005 - 00:46:43 EST

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 Received on Wed Jul 13 00:57:25 2005

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