[R] is it safe to replace every "<-" by "=" in R code?

Gabor Grothendieck ggrothendieck at gmail.com
Mon Jan 14 08:31:36 CET 2008


Its not related to scoping. f(b = 10) passes 10 as argument b
but f(b <- 10) assigns to variable b (which has nothing to do with
argument b) and then passes the result of the b<-10 expression (which is
10) to f.  Since no argument was specified it uses positional
matching and the first position is argument a.  Thus its the same
as f(10).  Note that f(b<-10) isthe same as f( (b <- 10) ) which may
make it clearer.

On Jan 14, 2008 2:12 AM, Mark Wardle <mark at wardle.org> wrote:
> On 13/01/2008, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
> > No.
> >
> > > f <- function(a = 3, b = 4) a-b
> > > f(b = 10)
> > [1] -7
> > > f(b <- 10)
> > [1] 6
> >
>
> I had to go and read (and re-read) the R manual on lexical scope to
> try and understand this since this example highlights a previously
> neglected "chasm" in my knowledge base!
>
> Why does that give the result it does?
>
> I can see that
> f(b <- 10) is equivalent to   f(assign("b"), 10))
>
> I can't work out whether that is interpreted within the parent
> environment or the function's own environment at the time of call. Why
> does R give the answer it does? This can't be a scope issue?  I would
> have expected either -1 or -7!
>
> Am I being completely dim?
>
> --
> Dr. Mark Wardle
> Specialist registrar, Neurology
> Cardiff, UK
>




More information about the R-help mailing list