[R] argh .. if/else .. why?
jim holtman
jholtman at gmail.com
Mon Feb 15 15:13:10 CET 2010
Check back in the archieves. This is a common question. The problem
is basically when input commands at the command line, when you hit the
carriage return it is assuming there is a complete command. 'if' not
followed by an 'else' is assumed to be complete and when you type the
'else' by itself it is unexpected. At the command line, always use
brackets or have the 'else' on the same line:
if (test) statement else statement #OK
if (test){
statement
} else {
statement
} #OK
Within a function, or a block like the 'for' loop, the statement is
not complete until the closing bracket, so internally it will be
parsed correctly, but just get into the habit of making sure the
if/else are on the same line or bracket.
On Mon, Feb 15, 2010 at 9:01 AM, Esmail <esmail.js at gmail.com> wrote:
> Hello, would someone please help explain the following inconsistency
> in the if/else statement to me?
>
> The format of the if/else #3 below is ok, but if/else #1 is not? (I get
> an "unexpected else" type error.) In order for it to work I have to use
> if/else #2
>
> Thanks .. maybe there is some reason for this, but this looks very
> inconsistent to me.
>
> R version 2.10.1 (2009-12-14)
> Ubuntu 9.04
>
> Esmail
>
>
> ---------------
>
> #if (ZELIG) ######## if/else #1
> # cat(sprintf("Zelig for %d runs - timeR\n", RUNS))
> #else
> # cat(sprintf("lme for %d runs - timeR\n", RUNS))
>
>
> if (ZELIG){ ####### if/else #2
> cat(sprintf("Zelig for %d runs - timeR\n", RUNS))
> } else
> {
> cat(sprintf("lme for %d runs - timeR\n", RUNS))
> }
>
>
> cat(date()," start - timeR\n")
>
> for(i in 1:RUNS)
> {
>
> if (ZELIG) ##### if/else #3
> do_Zelig()
> else
> do_lme()
>
>
> cat(i, ' - ', date(),"\n")
> }
>
> cat(date()," end - timeR\n")
> sink()
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
More information about the R-help
mailing list