[R] Is = now the same as <- in assigning values

Peter Dalgaard p.dalgaard at biostat.ku.dk
Fri Dec 19 01:27:02 CET 2008


Stavros Macrakis wrote:
> On Thu, Dec 18, 2008 at 1:37 PM, Wacek Kusnierczyk <
> Waclaw.Marcin.Kusnierczyk at idi.ntnu.no> wrote:
> 
>> Kenn Konstabel wrote:
>>>> ...foo({x = 2})
>> ...
>>
>> This is legal but doesn't do what you probably expect -- although
>>> documentation for `<-` says the value (returned by <-) is 'value' i.e.
>>> whatever is on the right side ...
> 
> What do you expect this to do that is different from what it does, namely
> assign 2 to x and call foo on the value 2, which is the same as the value of
> x?  As long as foo doesn't do tricks with substitute, all the following
> should be identical:
> 
>          foo(x<-2)
>          foo((x<-2))
>          foo((x=2))
>          foo({x=2})
>          foo({x<-2})
>          foo(a=(x=2))
>          {x=2; foo(invisible(x))}
>          {x<-2; foo(invisible(x))}
>          {x=2; foo(invisible(2))}
>          {x<-2; foo(invisible(2))}
>          foo(a=x<-2)
> 
.....
> 
> Of course, if foo *does* use substitute, all bets are off, because it would
> capture the argument as an unevaluated expression and could do whatever it
> wanted with it.

Also watch out for lazy evaluation. It is required that a is evaluated 
inside foo to have equivalence with the pre-assigning forms (and even 
so, things may happen in different order).

Consider

 > foo <- function(a){cat("hello, "); a}
 > foo(cat("world\n"))
hello, world





-- 
    O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
   c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
  (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907



More information about the R-help mailing list