On Fri, 13 Mar 2009, Paul Suckling 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.
That is most unfortunate for you.
Is this behaviour a bug?
No.
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?
No.
R is not ignoring several lines of an expression.
f <- a
+ b
+ c;
is three perfectly legitimate expressions over three lines. R evaluates
f<-a
then evaluates
+b
then evaluates
+c
For people who like semicolons, it's the same as if you had
f <- a;
+b;
+c;
The semicolons are just an alternative to a newline, so a semicolon at the end
of a line is purely cosmetic. Modifying the parser to require a semicolon to
terminate a statement would break essentially every piece of R code and
documentation in existence, so it's probably easier to change your house style.
You could fairly easily write a tool that parsed your scripts and checked that
all your expressions were either assignments or function calls and that the
top-level expressions did not include unary plus or minus.
-thomas
Thomas Lumley Assoc. Professor, Biostatistics
tlum...@u.washington.edu University of Washington, Seattle
______________________________________________
R-help@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.