[R] Problem with parser and if/else

Peter Dalgaard p.dalgaard at biostat.ku.dk
Thu Nov 13 15:05:12 CET 2003


"Brown, Simon" <simon.brown at 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 at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list