Re: [R] Problem with parser and if/else

About this list Date view Thread view Subject view Author view Attachment view

From: Peter Dalgaard (p.dalgaard@biostat.ku.dk)
Date: Fri 14 Nov 2003 - 01:05:12 EST


Message-id: <x2vfpomkiv.fsf@biostat.ku.dk>


"Brown, Simon" <simon.brown@metoffice.com> writes:

> Dear r-help people,
>
> could you confirm that this is correct behaviour for R? I am using RH9.
>
> the code:
> x1 <- 1:6
> t1 <- 5
> if (length(x1) >= t1) {
> cat("in the if \n")
> } else {
> cat("in the else\n")
> }
>
> runs fine:
> > source("test_if_else.R")
> in the if
> >
>
> but the code:
> x1 <- 1:6
> t1 <- 5
> if (length(x1) >= t1) {
> cat("in the if 2\n")
> }
> else {
> cat("in the else\n")
> }
>
> fails with the error:
> > source("test_if_else2.R")
> Error in parse(file, n, text, prompt) : syntax error on line 6
> >
>
> Could someone explain this to me please?

Again? This has been hashed over several times before. The basic issue
is whether a statement can be assumed to be syntactically complete at
the end of a line. It is fairly obvious what happens when you type the
same expressions at an interactive prompt:

> x1 <- 1:6
> t1 <- 5
> if (length(x1) >= t1) {
+ cat("in the if 2\n")
+ }
in the if 2
> else {
Error: syntax error
> cat("in the else\n")
in the else
> }
Error: syntax error

Notice that the first right curly brace is seen as terminating the if
construct. Otherwise, R would need to wait and check whether the
*next* line starts with an "else" which would certainly be confusing
in interactive use. So R assumes the expression is finished and
evaluates it. Then it gets an "else" keyword that it doesn't know what
to do with and barfs.

Files that are source()'ed are subject to the same restrictions as
code given as input. This is a fairly useful consistency requirement.

[Come to think of it, it is not entirely obvious that we couldn't have
"else ..." working like "if (TRUE) ..." or "if (FALSE) ..." depending
on the result of a previous if(). I suppose the issue is how to make
sure that there actually is a matching "if".]

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

______________________________________________ R-help@stat.math.ethz.ch mailing list https://www.stat.math.ethz.ch/mailman/listinfo/r-help


About this list Date view Thread view Subject view Author view Attachment view

This archive was generated by hypermail 2.1.3 : Thu 01 Jan 2004 - 09:20:41 EST