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

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Jan 14 08:54:38 CET 2008


On Mon, 14 Jan 2008, Mark Wardle 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

lexical scope does not come into this; S behaves the same way.

> 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))

Actually, to f(assign("b", 10)), and this matches the first argument, so 
that call is like (but see below)

assign("b", 10); f(b)

> 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?

Probably you don't know the rules:

Actual function arguments are evaluated in the calling (one sense of 
'parent', e.g. sys.parent) environments, *if* they are evaluated at all. 
(It is the latter than makes this sort of construction inadvisable.) 
However, default arguments are evaluated in the evaluation frame of the 
function (that is, as if they appeared in the body of the function).

So

> f <- function(a, b) NULL
> f(b <- 10)
NULL
> b
Error: object "b" not found

is correct, but most people don't know that.  Since the behaviour depends 
on f() which can be changed at a later date, I suggest that this 
construction should be avoided.


As for " <- " vs " = ": observation suggests that you will annoy fewest 
people if you use " <- ", *with the surrounding spaces*.  People who find 
" <- " annoying need to get over this, as that is what is used throughout 
the R code base and in the vast majority of packages -- and reading R code 
to understand the methods you use is an important skill.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list