[R] R multiline expression grief

jim holtman jholtman at gmail.com
Fri Mar 13 14:12:17 CET 2009


This is a perfectly legal expression:

f <- a
   + b
   + c;

Type it in a the console, and it will assign a to f and then print out
the values of b and c.  In parsing 'f <- a' that is a complete
expression.  You may be confused since you think that semicolons
terminate an expression; that is not the case in R.  If you write 'f
<- a +' and then continue on the next line, R recognizes that the
parsing of the expression is not complete and will continue looking.
So it is not a bug; just a misunderstanding of what the syntax is and
how it works.

There are similar questions when people type in the following type of
statements:

if (1 == 1) print (TRUE)
else print (FALSE)

At the console you get:

> if (1 == 1) print (TRUE)
[1] TRUE
> else print (FALSE)
Error: unexpected 'else' in "else"
No suitable frames for recover()
>

because the parsing of the 'if' is complete.  Instead you should be doing:

> if (1 == 1) {print (TRUE)
+ } else {print (FALSE)}
[1] TRUE
>

so the parse knows that the initial 'if' is not complete on the single line.

On Fri, Mar 13, 2009 at 8:55 AM, Paul Suckling <paul.suckling at gmail.com> wrote:
> Dear all.
>
> After much grief I have finally found the source of some weird
> discrepancies in results generated using R. It turns out that this is
> due to the way R handles multi-line expressions. Here is an example
> with R version 2.8.1:
>
> ----------------------------------------------------
> # R-script...
>
> r_parse_error <- function ()
> {
>  a <- 1;
>  b <- 1;
>  c <- 1;
>  d <- a + b + c;
>  e <- a +
>    b +
>    c;
>  f <- a
>    + b
>    + c;
>  cat('a',a,"\n");
>  cat('b',b,"\n");
>  cat('c',c,"\n");
>  cat('d',d,"\n");
>  cat('e',e,"\n");
>  cat('f',f,"\n");
> }
> ----------------------------------------------------
>> r_parse_error();
> a 1
> b 1
> c 1
> d 3
> e 3
> f 1
> ----------------------------------------------------
>
> As far as I am concerned f should have the value 3.
>
> This is causing me endless problems since case f is our house style
> for breaking up expressions for readability. All our code will need to
> be rechecked as a result. Is this behaviour a bug? If not, is it
> possible to get R to generate a warning that several lines of an
> expression are potentially being ignored, perhaps by turning on a
> strict mode which requires the semi-colons?
>
> Thank you,
>
> Paul
>
> ______________________________________________
> 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