-----Original Message-----
From: owner-r-devel@stat.math.ethz.ch
[mailto:owner-r-devel@stat.math.ethz.ch] On Behalf Of John Chambers
Sent: Friday, November 08, 2002 8:15 AM
To: bolker@zoo.ufl.edu
Cc: R development mailing list
Subject: Re: behavior of =
It's a real confusion, but don't blame it on the use of "="
as an assignment operator.
It's all the fault of having named arguments, which goes way
back to the dawn of time.
What you said (as opposed to what, of course, you meant) was
that the argument called "x" to "[" had the value of min(x).
The clue is that after evaluating the expression, x is
unchanged (distinctly NOT the case for the infamous C equivalent).
R> x <- runif(20)
R> y <- 1:20
R> y[x = min(x)]
numeric(0)
R> x
[1] 0.1452749 0.4936352 0.7872399 0.4377552 0.4072236
0.4416220 0.4748017 [8] 0.8523369 0.8870081 0.7401091
0.1480467 0.3367802 0.3825770 0.3596608 [15] 0.1040230
0.6873980 0.2974596 0.9955219 0.3217589 0.2199942
Unfortunately, the implementation of "[" doesn't check
argument names (plausibly a bug). To see the situation more
clearly, use the sort function, whose first argument is "x".
R> sort(x=min(x))
[1] 0.1040230
which is puzzling, but:
R> sort(y=5)
Error in sort(y = 5) : unused argument(s) (y ...)
All the same, it's a useful example for a "what went wrong" FAQ.
Ben Bolker wrote:
I probably didn't follow the discussion of allowing "=" as an
assignment operator closely enough, but I was a little bit
to discover today (using 1.6.0; I haven't upgraded to 1.6.1
x <- runif(20)
y <- 1:20
y[x=min(x)]
gives numeric(0) (because min(x) is non-integer).
x <- sample(1:20,20,TRUE)
y[x=min(x)]
is even worse -- it gives the "wrong" answer. I know exactly what's
going on here (the = in the subsetting statement above was
==), and I should have known better, but I felt like I was
in C again!
I know that the designers tried to build in safeguards (from the man
page):
the `=' is only allowed at the top level (that is, in
expression typed by the user) or as one of the
braced list of expressions.
These safeguards don't prevent the mishap shown above. Is
way to detect this case syntactically (check for assignments inside
subsetting operations??), or will I just have to train my
watch out for this possibility?